Javascript 返回一个没有删除元素的数组?使用 splice() 而不更改数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6824916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:20:09  来源:igfitidea点击:

Returning an array without a removed element? Using splice() without changing the array?

javascriptarrays

提问by mowwwalker

I want to do something like:

我想做类似的事情:

var myArray = ["one","two","three"];
document.write(myArray.splice(1,1));
document.write(myArray);

So that it shows first "one,three", and then "one,two,three". I know splice() returns the removed element and changes the array, but is there function to return a new array with the element removed? I tried:

这样它首先显示“一,三”,然后显示“一,二,三”。我知道 splice() 返回删除的元素并更改数组,但是是否有函数返回删除元素的新数组?我试过:

window.mysplice = function(arr,index,howmany){
    arr.splice(index,howmany);
    return arr;   
};

If I try:

如果我尝试:

var myArray = ["one","two","three"];
document.write(mySplice(myArray,1,1));
document.write(myArray);

It still changes myArray...

它仍然改变了 myArray ...

Please help.

请帮忙。

采纳答案by Neverever

as suggested by the answer below, here is a code snapshot

正如下面的答案所建议的,这是一个代码快照

var myArray = ["one", "two", "three"];
var cloneArray = myArray.slice();

myArray.splice(1, 1);

console.log(myArray);
console.log(cloneArray);

回答by mu is too short

You want slice:

你想要slice

Returns a one-level deep copy of a portion of an array.

返回数组一部分的一层深拷贝。

So if you

所以如果你

a = ['one', 'two', 'three' ];
b = a.slice(1, 3);

Then awill still be ['one', 'two', 'three']and bwill be ['two', 'three']. Take care with the second argument to slicethough, it is one more than the last index that you want to slice out:

然后,a仍然会['one', 'two', 'three']b['two', 'three']。不过要注意第二个参数slice,它比您要切出的最后一个索引多一个:

Zero-based index at which to end extraction. sliceextracts up to but not including end.

结束提取的从零开始的索引。slice最多提取但不包括end.

回答by Thai-Duong Nguyen

Use this:

用这个:

function spliceNoMutate(myArray,indexToRemove) {
    return myArray.slice(0,indexToRemove).concat(myArray.slice(indexToRemove+1));
}

回答by Rafael

I know this question is old, but this approach might come in handy.

我知道这个问题很老,但这种方法可能会派上用场。

var myArray = ["one","two","three"];
document.write(myArray.filter(function(v, index) { return index !== 1 })

or

或者

var myArray = ["one","two","three"];
document.write(myArray.filter(function(v, index) { return v !== "two" })

This uses the Array.filter()function and tests against either the index being 1 or the value being "two".

这将使用Array.filter()函数并针对索引为 1 或值为“二”进行测试。



现在,我不能保证这些解决方案的性能(因为它检查数组上的每个项目,Nguyen 的 answeranswer可能更有效),但如果你想做更复杂的事情并且更容易理解,它会更灵活。

回答by arthurDent

You can use the ES6 spread feature:

您可以使用 ES6 扩展功能:

let myArray = ['one','two','three'];
let mySplicedArray = [...myArray];
mySplicedArray.splice(1,1); 

console.log(myArray); /// ['one', 'two', 'three']
console.log(mySplicedArray); /// ['one', 'three']

回答by corysimmons

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const abc = ['aaa', 'bbb', 'ccc']
const ac = abc.filter(_ => _ !== 'bbb')

You'd want to do this so you have a non-mutated array.

你会想要这样做,所以你有一个非变异的数组。

I don't think performance is as good as something like slice+ concat, but worry about that if it becomes a problem. Until then, filteris really clean.

我认为性能不如slice+ 之类的好concat,但如果它成为问题,请担心。到那时,filter真的很干净。

回答by jfriend00

Instead of this:

取而代之的是:

document.write(myArray.splice(1,1));

why not just use:

为什么不只是使用:

document.write(myArray[1]);

splice()modifies the array in place by definition. See slice()if you want a copy.

splice()根据定义修改数组。看看slice()你是否想要一个副本。

回答by AlienWebguy

Why not just reference the index?

为什么不只引用索引?

var myArray = ["one","two","three"];
document.write(myArray[1] + '<br />');
document.write(myArray);

Example: http://jsfiddle.net/AlienWebguy/dHTUj/

示例:http: //jsfiddle.net/AlienWebguy/dHTUj/

回答by El Pane

I think the best approach to splice an element from array without mutating and without making a copy of itself is using filter:

我认为从数组中拼接元素而不发生变异且不复制自身的最佳方法是使用过滤器:

arr = ["one", "two", "three"]
elToRemove = "two"
filteredArr = arr.filter( n => n != elToRemove)

console.log(arr) // ["one", "two", "three"]
console.log(filteredArr) // ["one", "three"]

回答by vdegenne

I think the neatest way is to create a simple function, and bind the function to the Array prototype if you need global access.

我认为最巧妙的方法是创建一个简单的函数,如果需要全局访问,则将该函数绑定到 Array 原型。

Most of the answers provided to the question are wrong. People confuse returning one element of one array without modifying its content but what the OP needs is to return a clone of the array without one element.

该问题提供的大多数答案都是错误的。人们混淆了在不修改其内容的情况下返回一个数组的一个元素,但 OP 需要的是返回一个没有一个元素的数组的克隆。

Here's my solution :

这是我的解决方案:

let arr = ['one', 'two', 'three'];

/* functional */
window.cloneSlice = (arr, start, end) => {
  const _arr = arr.slice();
  _arr.splice(start, end);
  return _arr;
}
// usage
console.log(cloneSlice(arr, 1, 1)); // one, three
console.log(arr); // one, two, three

/* prototyped */
Array.prototype.cloneSlice = function (start, end) { return cloneSlice(this, start, end) }
// usage
console.log(arr.cloneSlice(1, 1)); // one, three
console.log(arr); // one, two, three