使用while循环在printArray函数中获取一个额外的未定义值
Getting an extra undefined value in printArray function using while loop
我是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
或类似的
建议阅读这些以备将来参考:
每个的排列
为什么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++;
}
}
相关文章:
- 变量转换为另一个“未定义”的变量
- getDataAsJSON()在PHP中是一个未定义的函数,但许多解释如何使用JSONP的网站都说要使用它
- 所以这是说我的法定对象中有一个未定义的变量
- 为什么在这个数组的末尾会有一个未定义的
- 为什么我得到一个未定义的回报
- Router.use()需要中间件函数,但得到了一个未定义的函数
- 使用jQuery'在数组中循环;s中的每一个都会在生成字符串时在开头产生一个未定义的值
- 如果定义了值,为什么会得到一个未定义的值?使用 eval()
- 无论如何,在Visual Studio智能感知中定义一个未定义的对象
- 角度过滤器分组依据过滤器返回一个“未定义”字段
- 如果我在 Filter() 函数中使用索引,我会得到一个未定义的引用错误吗?
- 另一个未定义的JavaScript问题
- 我得到一个未定义而不是文件名
- 为什么我的 push() 方法不断在我的数组中插入一个“未定义”的元素
- addEventListener 使用 for 循环给了我一个未定义的结果
- Promise.all 在完成之前返回一个未定义和解析的数组
- Angular JS给出了一个未定义的函数错误
- 我得到一个未定义的索引
- JS说我有一个未定义的对象.真的需要一些帮助来解决这个问题吗
- Ajax 调用给了我一个未定义 - 未定义的错误