删除JavaScript中的数组元素-删除VS拼接使用这个delete操作者在数组元素上,而不是使用这个Array.splice方法?例如:myArray = ['a', 'b', 'c', 'd'];delete myArray[1];// ormyArray.splice (1, 1);如果我可以像删除对象一样删除数组元素,那么为什么还要使用Splice方法呢?
4 回答
心有法竹
TA贡献1866条经验 获得超5个赞
delete
> myArray = ['a', 'b', 'c', 'd'] ["a", "b", "c", "d"]> delete myArray[0] true> myArray[0] undefined
undefined
empty
> myArray[0] undefined> myArray [empty, "b", "c", "d"]
myArray.splice(start, deleteCount)
> myArray = ['a', 'b', 'c', 'd'] ["a", "b", "c", "d"]> myArray.splice(0, 2) ["a", "b"]> myArray ["c", "d"]
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
Array.emove()方法
约翰·雷西格Array.remove
// Array Remove - By John Resig (MIT Licensed)Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest);};
// Remove the second item from the arrayarray.remove(1);// Remove the second-to-last item from the arrayarray.remove(-2); // Remove the second and third items from the arrayarray.remove(1,2); // Remove the last and second-to-last items from the arrayarray.remove(-2,-1);
元芳怎么了
TA贡献1798条经验 获得超7个赞
myArray = ['a', 'b', 'c', 'd']; delete myArray[2];for (var count = 0; count < myArray.length; count++) { alert(myArray[count]);}
myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);for (var count = 0; count < myArray.length; count++) { alert(myArray[count]);}
温温酱
TA贡献1752条经验 获得超4个赞
splice
delete
'c'
items
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];while (items.indexOf('c') !== -1) { items.splice(items.indexOf('c'), 1);}console.log(items); // ["a", "b", "d", "a", "b", "d"]items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];while (items.indexOf('c') !== -1) { delete items[items.indexOf('c')];}console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
添加回答
举报
0/150
提交
取消