简体   繁体   English

数组中的字符串不会在HTML中显示为字符串

[英]Strings in array not appearing as strings in HTML

First, my HTML: 首先,我的HTML:

<p id="p"></p>

<input id="input" />

<button onclick="fill()">Fill</button>

Then my Javascript: 然后我的Javascript:

function fill() {
    var x = document.getElementById('input').value;
    var y = x.split('');
    for (var i = 0; i < y.length; i++) {
        if (i == 0) {
            setTimeout(function() {
                document.getElementById('p').innerHTML = y[i];
            },(i * 50));
        }

        setTimeout(function() {
            document.getElementById('p').innerHTML += y[i];
        },(i * 50));
    }
}

What it does is take text from a textfield, cut each character including spaces into an array, then loop through the array, displaying each character at 50ms intervals. 它的作用是从文本字段中取出文本,将包含空格的每个字符切割成数组,然后遍历数组,以50ms的间隔显示每个字符。 The effect is supposed to look like it is typing itself out. 该效果应该看起来像是在打字。

The effect works fine, but the values of the array don't seem to be. 效果很好,但数组的值似乎不是。 If I were to type "abc123" then I would expect that to come right back out, but instead I get: 如果我输入“abc123”那么我希望它会立即退出,但我会得到:

undefinedundefinedundefinedundefinedundefinedundefined undefinedundefinedundefinedundefinedundefinedundefined

Using console.log() , when I check the array it looks fine, when I check the typeof of the individual array values I get string , but when I check the typeof for the array, I get object . 使用console.log() ,当我检查数组它看起来很好,当我检查单个数组值的typeof我得到string ,但当我检查数组的typeof ,我得到object Maybe this is what's wrecking it... 也许这就是破坏它的原因......

I have tried use toString() on the y[i] which just spits out "[object Window]", I have tried defining the array like this var y = new Array; 我已经尝试在y[i]上使用toString() ,它只是吐出“[object Window]”,我试着像这样定义数组var y = new Array; and then doing the split() , nothing works. 然后做split() ,什么都行不通。 I am at a complete loss. 我完全失去了。 Really would love some help here. 真的很想在这里得到一些帮助。 Thanks! 谢谢!

I believe there must be closure problem. 我相信必须有封闭问题。 Try this js code. 试试这个js代码。 I wrapped everything inside loop in a IIFE function. 我在IIFE函数中将所有内容包装在循环内。 I think it is well explained here Please explain the use of JavaScript closures in loops 我认为这里有很好的解释请解释在循环中使用JavaScript闭包

<script>
  function fill() {
      var x = document.getElementById('input').value;
      var y = x.split('');
      for (var i = 0; i < y.length; i++) {
        (function(i){
          if (i == 0) {
              setTimeout(function() {
                  document.getElementById('p').innerHTML = y[i];
              },(i * 50));
          }

          setTimeout(function() {
              document.getElementById('p').innerHTML += y[i];
          },(i * 50));
        })(i);
      }
  }
</script>

By calling setTimeout you're scheduling something to happen in the future. 通过调用setTimeout,您将安排将来发生的事情。 By the time the function you're delaying with setTimeout is executed, the loop has executed all the way through and i is now equal to y.length . 当你用setTimeout延迟执行的函数时,循环一直执行, i现在等于y.length So if you input test when the function executes it tries to add y[4] as a letter which is undefined . 因此,如果在函数执行时输入test ,则尝试将y[4]添加为undefined的字母。 To fix it, you can do something like this: 要修复它,你可以这样做:

 function fill() { var x = document.getElementById('input').value; var y = x.split(''); console.log(y); for (var i = 0; i < y.length; i++) { timeOutAdd(y[i], i*50) } } function timeOutAdd(c, delay){ setTimeout(function() { document.getElementById('p').innerHTML += c; }, delay); } 
 <p id="p"></p> <input id="input" /> <button onclick="fill()">Fill</button> 

By adding the timeOutAdd function which is called immediately instead of delayed we can hang on to the values of the parameters until the setTimeout function runs. 通过添加立即调用而不是延迟调用的timeOutAdd函数,我们可以挂起参数的值,直到setTimeout函数运行。

Note: I also removed the second call to setTimeout, it wasn't necessary and caused a bug where the first character of the string was output twice. 注意:我还删除了对setTimeout的第二次调用,没有必要,并导致一个错误,其中字符串的第一个字符输出两次。

This solves the closure problem, plus it simplifies the logic for outputting the data. 这解决了闭包问题,并且简化了输出数据的逻辑。 No need for splitting the string into an array: 无需将字符串拆分为数组:

 function fill() { var x = document.getElementById('input').value, p = document.getElementById('p'); for(var i = 0; i < x.length; i++) { (function(i) { setTimeout( function() { p.innerHTML= x.substr(0, i+1); }, i*50 ) })(i); } } 
 <p id="p"></p> <input id="input" value="abcde" /> <button onclick="fill()">Fill</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM