来自edabit的简单for循环错误,循环返回未定义

时间:2020-05-12 21:03:51

标签: loops

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

function isFourLetters(arr) {
    let newArray = [];
    for (let i = 0; i < arr.length; i++){
        if (arr[i].length === 4){
            newArray.push(arr[i]);
        }
    }
}

1 个答案:

答案 0 :(得分: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));

相关问题