记录数组索引,而不是值(JavaScript) -为什么?

Logging array indices, not values (JavaScript) - why?

本文关键字:JavaScript 为什么 索引 数组 记录      更新时间:2023-09-26

下面是我的脚本:

var alphabet = ["A", "B", "C", "D", "3", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
var str = [];
for (i=0; i<alphabet.length; i++) {
    str.push(i);
    console.log(str.join(""));
}

输出的是str的下标(0,01,012…)而不是值(A, AB, ABC…)。这是怎么回事?

您在循环中出现错误(push(i)而不是push(alphabet[i]))。正确的循环:

for (i=0; i<alphabet.length; i++) {
    str.push(alphabet[i]);
    console.log(str.join(""));
}