访问数组中最后一个元素时输出“未定义”

问题描述 投票:0回答:1

以下代码应该查找并打印数组中的最后一个元素,但运行时仅输出“未定义”。

// 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],但发生了同样的错误。

javascript arrays indexing undefined element
1个回答
0
投票

JS中的数组是从

0
开始索引的。你可以自己看一下
Array.prototype.keys()
:

let myArray = ['apples', 'oranges', 'watermelons'];
for(const index of myArray.keys()){
  console.log(index);
}

© www.soinside.com 2019 - 2024. All rights reserved.