javascript - 使用 while 循环在 printArray 函数中获取额外的未定义值

标签 javascript

我是 JavaScript 新手,我正在尝试编写一个简单的函数来使用 while 语句打印数组元素,但最后我得到了一个额外的未定义值。任何帮助将不胜感激

代码是:

var a = [1, 3, 6, 78, 87];

function printArray(a) {

    if (a.length == 0) {
        document.write("the array is empty");
    } else {
        var i = 0;
        do {
            document.write("the " + i + "element of the array is " + a[i] + "</br>");

        }
        while (++i < a.length);
    }
}

document.write(printArray(a) + "</br>");

输出是:

the 0element of the array is 1
the 1element of the array is 3
the 2element of the array is 6
the 3element of the array is 78
the 4element of the array is 87
undefined

我如何获得未定义的值?我是否跳过任何​​索引?提前致谢!

最佳答案

发生这种情况的原因是因为您的 printArray函数没有返回任何值,这意味着它实际上返回 undefined

您可以通过两种方式解决此问题:

  1. 更改document.write(printArray(a) + "</br>");printArray(a);document.write("<br/>") ]
  2. 让你的 printArray 返回一个字符串而不是 document.write并保留您的其他代码

更推荐第二种方式,还要注意使用 document.write也不推荐,尝试设置document.body.innerHTML或类似的东西

建议您阅读这些内容以供将来引用:

Array.forEach

Why is document.write a bad practice

关于javascript - 使用 while 循环在 printArray 函数中获取额外的未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36482809/

相关文章:

javascript - 调试 meteor 客户端时,如何查看集合或游标内容?

javascript - curry lodash api方法

javascript - Firestore 获取已查询文档的路径

javascript - 如何使用 gulp 构建 JavaScript 包?

javascript - jQuery 中的 bind() 和 rebind() 与常规 onclick 有何不同?

javascript - ng-repeat 中的 ng-click,未正确格式化值

javascript - AngularJS 自定义所需文本

JavaScript 图遍历库

javascript - Safari 是否支持 javascript window.onerror?

javascript - 在 Node.js 中使用 "global"