javascript - 函数中缺少元素

标签 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));

您能否对此进行分析并提供一些反馈?

最佳答案

函数末尾缺少 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));

关于javascript - 函数中缺少元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566022/

相关文章:

javascript - ES6 导入/导出如何与 CommonJS 导出/require 一起使用

javascript - 如何在React中访问无状态功能组件中的props.children?

c++ - 为什么 OpenGL 函数不使用模板?

swift - 调用结果未使用

javascript - 带有上一个、暂停和下一个按钮的 JS 文本循环

javascript - EaselJS:为什么缓存会使我的渲染速度变慢?

sql - 比较 PostgreSQL 中的两个数组

混淆结果 : Array of pointers in C

c - 为什么我不能打印这个指针的值?

ios - 跳过swift ViewController viewDidDisappear等主要功能