[英]Removing JavaScript array item without built in functions?
How can I remove an item from a JavaScript array without using built in functions like pop() and splice()?如何在不使用 pop() 和 splice() 等内置函数的情况下从 JavaScript 数组中删除一个项目?
You can use Array rest parameter and destructuring for that您可以使用数组rest 参数和解构
if you want to delete something from beginning如果你想从头开始删除一些东西
let arr = [1, 2, 3, 4]; let [c, d, ...newarr] = arr; console.log(newarr)
If you don't care about the array being reindexed, you can use the delete
operator , but it will leave an undefined
entry where the deleted value was, and the .length
of the array will still be the same as before:如果你不关心数组被重新索引,你可以使用
delete
operator ,但它会在删除值所在的位置留下一个undefined
的条目,并且数组的.length
仍然与以前相同:
const arr = [1, 2, 3, 4, 5]; console.log(arr.length, `[${ arr.join(', ') }]`); delete arr[2]; console.log(arr.length, `[${ arr.join(', ') }]`);
If you want to delete elements from the end, you can manually update the .length
property of the array:如果要从末尾删除元素,可以手动更新数组的
.length
属性:
const arr = [1, 2, 3, 4, 5]; console.log(arr.length, `[${ arr.join(', ') }]`); arr.length = 3;; console.log(arr.length, `[${ arr.join(', ') }]`);
Otherwise, you can use a loop to go through the original elements and push the ones you want to keep to a separate array:否则,您可以通过原始元素使用到 go 的循环,并将要保留的元素推送到单独的数组:
const arr = [1, 2, 3, 4, 5]; console.log(arr.length, `[${ arr.join(', ') }]`); const even = []; for (let n of arr) { if (n % 2 === 0) even.push(n); } console.log(even.length, `[${ even.join(', ') }]`);
You can use slice
你可以使用
slice
const arr = [1,2,3,4,5];
console.log(arr.slice(0,4)); // [1,2,3,4];
console.log(arr.slice(1,5)); // [2,3,4,5];
Thanks to Paul in the comment section for suggesting arr.length--;
感谢 Paul 在评论区建议
arr.length--;
. . Since I was using pop() previously the item I wanted to remove was already at the end so it worked out perfectly.
因为我之前使用的是 pop() ,所以我想删除的项目已经在最后,所以它完美地解决了。
You could create your own method like below:您可以创建自己的方法,如下所示:
Array.prototype.removeItem = function(item) {
for (i = 0; i < this.length; i++) {
if (this[i] === item) {
for (var j = i; j < this.length - 1; j++) {
this[j] = this[j + 1];
}
this.length = this.length - 1
return;
}
}
}
var items = ['a', 'b', 'c', 'd'];
items.removeItem('c');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.