以下代码应该查找并打印数组中的最后一个元素,但运行时仅输出“未定义”。
// The following code aims to access the element at the last index of an array.
let myArray = ['apples', 'oranges', 'watermelons'];
let index = 3;
let element = myArray[index];
console.log(element);
我尝试将 myArray[index] 更改为 myArray[3],但发生了同样的错误。
JS中的数组是从
0
开始索引的。你可以自己看一下Array.prototype.keys()
:
let myArray = ['apples', 'oranges', 'watermelons'];
for(const index of myArray.keys()){
console.log(index);
}