edabit的循环错误很简单,用于循环返回未定义

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

我不知道我的JavaScript for循环有什么问题。有人可以指出我的错误吗?

`function isFourLetters(arr) {
    let newArray = [];
    for (let i = 0; i < arr.length; i++){
        if (arr[i].length === 4){
            newArray.push(arr[i]);
        }
    }
}`
loops
1个回答
0
投票

我认为您只是在功能中缺少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));
© www.soinside.com 2019 - 2024. All rights reserved.