Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate string array error, runs for first item's letters

I have a simple array loop, runs perfect in jsFiddle showing all items, see https://jsfiddle.net/8odoros/b27ocs4d/1/

What's strange is that putting the same script here as a snippet runs by letter, showing the first string letter by letter. I feel stupid, am I missing something? Check it out:

var name = ['Helen','Jim','Thomas','Luke','Theodore'];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
	var newHtml = name[i]+'&emsp;'+i+'</br>';
	div.innerHTML = div.innerHTML + newHtml;  	
}
<div id="cards"></div>
like image 282
Theodore K. Avatar asked Jan 16 '26 23:01

Theodore K.


2 Answers

Word name is a reserved word (as @prasad answered) in javascript that why your code was not working as expected.

See below code, after changing name with names. Its seems working as was working in jsfiddle.

var names = ['Helen','Jim','Thomas','Luke','Theodore'];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
	var newHtml = names[i]+'&emsp;'+i+'</br>';
	div.innerHTML = div.innerHTML + newHtml;  	
}
<div id="cards"></div>

Note: name can only be used as local variable inside a function or iife and can not used as global varibale.

like image 149
pradeep1991singh Avatar answered Jan 19 '26 16:01

pradeep1991singh


Try any one of the function its working. name is reserved word of javascript.But applied with in function .Its not act as a reserved word.This is one of the way preventing the action.

(function () {
var name = ["Helen","Jim","Thomas","Luke","Theodore"];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
  var newHtml = name[i]+'&emsp;'+i+'</br>';
	div.innerHTML = div.innerHTML + newHtml;  	
}
  })()
<div id="cards"></div>
like image 45
prasanth Avatar answered Jan 19 '26 16:01

prasanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!