了解JS中删除操作员的理解



var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
if (3 in trees) {
  console.log(trees[3]);
}
else {
  console.log("not found");
}

答案显示"找不到",但没有显示不确定的。这是为什么?即使在最后,当我们计算出显示的数组的长度时,5而不是4。为什么?请用示例解释。

答案显示"找不到",但没有显示不确定的。为什么是?

您删除了名为 3的属性(这与现有的属性不同,但具有值undefined)。由于它不存在,因此不是in数组。因此,您击中else分支。

,甚至在末尾,当我们计算该数组的长度时,它显示为5而不是4

长度是以整数命名的最高属性的名称,再加上一个。

您的代码中有一个语法错误。您声明

var tress

然后您尝试删除非现有变量:

删除树[3]

删除命令将从数组中删除一个条目,并使其不确定。

可以在此处找到有关删除的更多详细信息。

在您的代码中添加了注释,以提供更好的说明

let tress = ["redwood", "bay", "cedar", "oak", "maple"];
// an array is an object with properties as index of the elements
// this prints all the keys currently in the object
console.log(Object.keys(tress));
delete tress[3];
console.log(tress);
// Now You can see that the property 3 has been removed from the array
console.log(Object.keys(tress));
if (3 in tress) {
    console.log(tress[3]);
}
else {
console.log("not found");
}
// Since the the property does not exist hence it prints not found

如果指定的属性或指定的对象中指定的属性或属性列表,则运算符返回true。由于您删除了该属性,您将获得false

以下代码返回"找不到",因为"橡木"已从数组中删除。

var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
if (trees.indexOf("oak") > 0){
    console.log(trees[3]);
}
else {
console.log("not found");
}

最新更新