函数

时间:2017-03-02 21:10:27

标签: javascript arrays function undefined

此函数应创建并显示带数字的数组。有一些元素缺失会阻止此数组显示,从而实现“console.log”假设:

function createArray(number) {
    var newArray = [/*10*/];

    for(var counter = 1; counter <= number; counter++) {
        newArray.push(counter);
    }
}

console.log("table with numbers up to 6 = " + createArray(6));
console.log("table with numbers up to 1 = " + createArray(1));
console.log("Testing negatives (should display an empty array) " + createArray(-6));
console.log("Testing 0 (should display an empty array) " + createArray(0));

你能分析一下并提供一些反馈吗?

2 个答案:

答案 0 :(得分:1)

您在功能结束时缺少return newArray;。如果没有return语句,则该函数默认返回undefined

function createArray(number) {
    var newArray = [/*10*/];

    for(var counter = 1; counter <= number; counter++) {
        newArray.push(counter);
    }
    return newArray;
}

console.log("table with numbers up to 6 = " + createArray(6));
console.log("table with numbers up to 1 = " + createArray(1));
console.log("Testing negatives (should display an empty array) " + createArray(-6));
console.log("Testing 0 (should display an empty array) " + createArray(0));

答案 1 :(得分:0)

嗯,你的函数没有任何问题,只是你没有返回创建的数组,只需添加:

在函数结束时

return newArray,请点击这个:

function createArray(number) {
    var newArray = [/*10*/];

    for(var counter = 1; counter <= number; counter++) {
        newArray.push(counter);
    }
     return newArray;
}