当我使用这段代码时,我遇到了这个问题,(未捕获的类型错误:无法读取未定义的属性(读取“startsWith”))

问题描述 投票:0回答:2
let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;

// Output
"1 => Sayed"
"2 => Mahmoud"

while (index < friends.length) {
    index++
    if (typeof friends[index] === "number") {
        continue;
    }
    if (friends[index].startsWith(friends[counter][counter])) {
      continue;
    }
    console.log(friends[index])
}

我希望得到这个输出。

“1 => 赛义德” “2 => 马哈茂德”

但是控制台给了我这个错误 Uncaught TypeError: Cannot read properties of undefined (reading 'startsWith')

javascript console undefined startswith
2个回答
1
投票

您的问题是,您在循环开始而不是结束时递增索引。这意味着,当您位于索引 6 时,它仍然满足 while 条件,然后在循环中递增到 7,这对于 friends 数组来说是越界的。我的解决方案是从 while 循环切换到 for 循环。

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let counter = 0;

for (let index = 0; index < friends.length; index++) {
    if (typeof friends[index] === "number") {
        continue;
    }
    if (friends[index].startsWith(friends[counter][counter])) {
      continue;
    }
    console.log(friends[index])
}


0
投票

尝试将 friends[index] 添加到您的支票中。另外,你的循环条件应该是 friends.length - 1

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;

while (index < friends.length -1) {
    index++
    if (typeof friends[index] === "number") {
        continue;
    }
    if (friends[index] && friends[index].startsWith(friends[counter][counter])) {
      continue;
    }
    console.log(friends[index])
}
© www.soinside.com 2019 - 2024. All rights reserved.