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

Getting an extra undefined value in printArray function using while loop

本文关键字:一个 未定义 循环 while printArray 函数 获取 使用      更新时间:2024-03-18

我是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或类似的

建议阅读这些以备将来参考:

每个的排列

为什么document.write是一种糟糕的做法

var a = [1, 3, 6, 78, 87];
function myFunction() {
    var i = 0;
    while (i < a.length) {
        document.write("the " + i + "element of the array is " + a[i] + "</br>");
        i++;
    }
}