英文:
when i use this code i faced this problem, (Uncaught TypeError: Cannot read properties of undefined (reading 'startsWith'))
问题
I expect to get this output:
"1 => Sayed"
"2 => Mahmoud"
但控制台给我报错:Uncaught TypeError: Cannot read properties of undefined (reading 'startsWith')
英文:
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(friends0+网站访问量0+网站访问量)) {
continue;
}
console.log(friends[index])
}
And i Expect to get this output.
"1 => Sayed"
"2 => Mahmoud"
but console gave me this error Uncaught TypeError: Cannot read properties of undefined (reading 'startsWith')
答案1
得分: 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]);
}
英文:
Your problem is, that you increment the index at the start of the loop instead of at the end. This means, that when you are at index 6 it still satisfys the while condition and then in the loop gets incremented to 7 which is outofbounds for the friends Array. My solution would be to switch from a while loop to a for loop.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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(friends0+网站访问量0+网站访问量)) {
continue;
}
console.log(friends[index])
}
<!-- end snippet -->
答案2
得分: 0
Try adding friends[index] to your check. Also, your loop condition should be 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(friends0+网站访问量0+网站访问量)) {
continue;
}
console.log(friends[index])
}
英文:
Try adding friends[index] to your check. Also, your loop condition should be 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(friends0+网站访问量0+网站访问量)) {
continue;
}
console.log(friends[index])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论