mow*_*ker 35 javascript arrays
我想做的事情如下:
var myArray = ["one","two","three"];
document.write(myArray.splice(1,1));
document.write(myArray);
Run Code Online (Sandbox Code Playgroud)
因此它首先显示"一,三",然后是"一,二,三".我知道splice()返回被删除的元素并更改数组,但是是否有函数返回一个删除了元素的新数组?我试过了:
window.mysplice = function(arr,index,howmany){
arr.splice(index,howmany);
return arr;
};
Run Code Online (Sandbox Code Playgroud)
如果我尝试:
var myArray = ["one","two","three"];
document.write(mySplice(myArray,1,1));
document.write(myArray);
Run Code Online (Sandbox Code Playgroud)
它仍然会改变myArray ......
请帮忙.
mu *_*ort 39
你想要slice:
返回数组的一部分的一级深层副本.
所以,如果你
a = ['one', 'two', 'three' ];
b = a.slice(1, 3);
Run Code Online (Sandbox Code Playgroud)
然后,a仍然会['one', 'two', 'three']和b会['two', 'three'].但是要注意第二个参数slice,它比你想要切出的最后一个索引多一个:
基于零的索引,用于结束提取.
slice提取但不包括end.
Nev*_*ver 27
如下面的答案所示,这是一个代码快照
var myArray = ["one", "two", "three"];
var cloneArray = myArray.slice();
myArray.splice(1, 1);
console.log(myArray);
console.log(cloneArray);Run Code Online (Sandbox Code Playgroud)
小智 12
用这个:
function spliceNoMutate(myArray,indexToRemove) {
return myArray.slice(0,indexToRemove).concat(myArray.slice(indexToRemove+1));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用ES6传播功能:
let myArray = ['one','two','three'];
let mySplicedArray = [...myArray];
mySplicedArray.splice(1,1);
console.log(myArray); /// ['one', 'two', 'three']
console.log(mySplicedArray); /// ['one', 'three']
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
\nconst oneTwoThree = [\'one\', \'two\', \'three\'] // original array\n\n// `filter()` (like most array functions) iterates over every item in the array.\n// Whatever returns true here is copied to a new array (the `oneThree` variable).\n// `item !== \'two\'` returns true for everything except \'two\'\nconst oneThree = oneTwoThree.filter(item => item !== \'two\')\n\nconsole.log(oneTwoThree) // [\'one\', \'two\', \'three\'] \xe2\x80\x94 the original, unscathed, array\nconsole.log(oneThree) // [\'one\', \'three\'] \xe2\x80\x94 a copy of the original, sans the value you wanted to remove\nRun Code Online (Sandbox Code Playgroud)\n你想要这样做,这样你就有了一个非变异的数组。
\n\n\n我认为性能不如
\nslice+之类的好concat,但担心它是否会成为问题(除非您正在处理数组中的数万个元素,否则可能不会)。直到那时,filter就真的干净了。
\n\n另请注意,这将从数组中删除该元素的所有实例
\ntwo,因此请确保数组中没有重复项,这些重复项可能会无意中被这种方法吞噬。
我知道这个问题很古老,但是这种方法可能会派上用场。
var myArray = ["one","two","three"];
document.write(myArray.filter(function(v, index) { return index !== 1 })
Run Code Online (Sandbox Code Playgroud)
要么
var myArray = ["one","two","three"];
document.write(myArray.filter(function(v, index) { return v !== "two" })
Run Code Online (Sandbox Code Playgroud)
这将使用该Array.filter()函数并针对索引为1或值为“二”的数据进行测试。