javascript - Can't display array output -


<script type="text/javascript"> function show(){      var word = document.getelementbyid("inp").value;     var letters = [];     for(i=0; i<=word.length; i++){         letters = word.substring(i,i+1);     }     document.getelementbyid("div").innerhtml = letters[0];      //setinterval(); }  </script> </head>  <body>  <input type="text" id="inp" /> <button onclick="show()">show</button> <br> <div id="div"></div>  </body> 

the output of "letters[0]" showing undefined. want create array, where, let's if input "hello", then, output like:

letters[0] = "h" letters[1] = "e" letters[2] = "l" .... 

and also, add setinterval() function it, displays letters, 1 one, delay.

thanks!

use push method add elements in array

replace

letters = word.substring(i,i+1); 

by

letters.push(word.substring(i,i+1)); 

demo

function show() {    var word = document.getelementbyid("inp").value;      var letters = [];    (i = 0; < word.length; i++) {      letters.push(word.substring(i, + 1));    }      var = 0;    var interval = setinterval(function() {      document.getelementbyid("div").innerhtml = letters[i];      ++i === letters.length && clearinterval(interval);    }, 250);  }
<input type="text" id="inp" />  <button onclick="show()">show</button>  <br>  <div id="div"></div>


to array of individual letters can use split

var div = document.getelementbyid("div"); // cache    function show() {    var word = document.getelementbyid("inp").value; // latest value      var letters = word.split(''), // split every character , store in letters array      = 0; // initialization 0      div.innerhtml = ''; // clear previous text      var interval = setinterval(function() {      div.innerhtml += letters[i]; // append character        ++i === letters.length && clearinterval(interval); // clear interval after appending characters    }, 100); // call function after every 100 milliseconds  }
<input type="text" id="inp" />  <button onclick="show()">show</button>  <br>  <div id="div"></div>


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -