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.为什么呢?请用例子说明。
答案 0 :(得分:1)
答案显示"未找到"但不显示未定义。那是为什么?
您删除了名为3
的属性(这与现有属性不同,但值为undefined
)。由于它不存在,因此数组不是in
。所以你点击else
分支。
即使在最后,当我们计算它所显示的数组的长度时,5而不是4
length是以整数命名的最高属性的名称加1。
答案 1 :(得分:0)
为您的代码添加了评论以获得更好的解释
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
如果指定的属性或属性列表在指定的对象中,则in运算符返回true。由于您删除了该属性,因此会出现错误
答案 2 :(得分:0)
答案 3 :(得分:0)
以下代码返回"未找到"因为"橡树"已从数组中删除。
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
if (trees.indexOf("oak") > 0){
console.log(trees[3]);
}
else {
console.log("not found");
}