【问题标题】:Getting an extra undefined value in printArray function using while loop使用 while 循环在 printArray 函数中获取额外的未定义值
【发布时间】:2016-04-07 17:05:27
【问题描述】:

我是 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

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

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

    1. document.write(printArray(a) + "&lt;/br&gt;"); 更改为printArray(a);document.write("&lt;br/&gt;")]
    2. 让您的 printArray 返回一个字符串,而不是执行 document.write 并保留您的其他代码

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

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

    Array.forEach

    Why is document.write a bad practice

    【讨论】:

      【解决方案2】:
      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++;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-16
        • 2021-06-23
        • 2015-12-26
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        • 2020-11-03
        • 1970-01-01
        相关资源
        最近更新 更多