我有一个关于数组中的空和未定义的问题
请查看我的代码底部
const arr = []
arr[1]=1
arr[2]=2
arr[3]=3
arr[5]=5
console.log(arr[4])// console: undefined
console.log(arr)// console: [empty, 1,2,3,empty,5]
所以我不明白两个 colsole 结果之间的区别
为什么 console.log(arr[4]) 未定义,但 console.log(arr) 的索引 4 为空?
请帮助我谢谢
当您读取不存在的属性时,您会得到值
undefined
。这是标准的 JS。
当您记录整个数组时,您没有显式读取属性,因此控制台有助于区分“没有值”和“显式具有
undefined
值”。
empty
这个词是浏览器控制台界面添加的。
未分配的数组元素的正确状态是
undefined
- 当您尝试访问它时,这是由 JS 提供给您的。除此之外,未分配的数组元素的解释取决于解释它的系统。
以下是一些示例:
let arr = new Array(2);
console.log(arr[0]); //undefined
console.log(arr); //In SO - [undefined, undefined]. In browser [empty x 2]
console.log(JSON.stringify(arr)); // [null, null]