我不知道我的JavaScript for循环有什么问题。有人可以指出我的错误吗?
`function isFourLetters(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i++){
if (arr[i].length === 4){
newArray.push(arr[i]);
}
}
}`
我认为您只是在功能中缺少return newArray;
。
这是您的代码的可运行示例,在函数内添加了return newArray;
:
function isFourLetters(arr) {
let newArray = [];
for (let i = 0; i < arr.length; i++){
if (arr[i].length === 4){
newArray.push(arr[i]);
}
}
return newArray; // This is the value that the function returns when called
}
let exampleArray1 = ["abc", "abcd", "abcde", "bcde"];
let exampleArray2 = ["wxy", "wxyz", "xyz", "test"];
console.log(isFourLetters(exampleArray1));
console.log(isFourLetters(exampleArray2));