我是 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
您可以通过两种方式解决此问题:
- 更改
document.write(printArray(a) + "</br>");
至printArray(a);document.write("<br/>")
] - 让你的 printArray 返回一个字符串而不是
document.write
并保留您的其他代码
更推荐第二种方式,还要注意使用 document.write
也不推荐,尝试设置document.body.innerHTML
或类似的东西
建议您阅读这些内容以供将来引用:
关于javascript - 使用 while 循环在 printArray 函数中获取额外的未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36482809/