简体   繁体   English

使用删除运算符

[英]Using the delete operator

I'm reading the delete unary operator talked about near bottom of page here ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Unary )我正在阅读此处页面底部附近谈到的delete一元运算符( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Unary

It says deleting an item from an array will make the item undefined .它说从数组中删除一个项目将使项目undefined However, as the code below shows, we cannot loop over this undefined item like we can do with a fresh array with the explicit value of undefined as one of its items.然而,正如下面的代码所示,我们不能像使用一个新数组一样循环这个undefined的项目,其中一个显式值为undefined的新数组是它的项目之一。

Is this just a quirk or is there more to read into here?这只是一个怪癖还是这里有更多需要阅读的内容? It doesn't seem meaningful to describe the deleted item as undefined when it's not treated like undefined .当它不被视为undefined时,将已删除的项目描述为undefined似乎没有意义。

 let a = [1, 2, 3]; console.log("untampered-with array:", a); delete a[0]; console.log("array after first item deleted:", a); a.forEach(element => { console.log("looping over each item and printing it:", element); }); b = [undefined, 1, 2]; b.forEach(element => { console.log("looping over each item of array with undefined explicitly declared:", element); });

It might also be worth mentioning that in Visual Studio Code, when we print out a after the first item is deleted, it does not show the first item as undefined (like it does on the Stack Overflow code simulator).还可能值得一提的是,在 Visual Studio Code 中,当我们在删除第一项后打印出a时,它不会将第一项显示为未定义(就像在 Stack Overflow 代码模拟器上一样)。 It shows this:它显示了这一点: 在此处输入图像描述

You can use splice method to remove array items instead of using delete.您可以使用 splice 方法来删除数组项,而不是使用 delete。

You can either use splice您可以使用拼接

let b = a.splice(0, 1)

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/splice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/splice

or filter过滤

let b = a.filter((item, i) => { return i !== 0 })

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter

In both case, b is a new array without the item indexed at 0.在这两种情况下, b都是一个新数组,其中没有索引为 0 的项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM