Displaying array elements using JavaScript

I am trying to display elements of a JavaScript array. The code:

var name = ["one" , "two"]; window.onload = function(){ document.getElementById('MinamaisVards').innerHTML=name[1]; } 

Can someone tell me why it displays the letter "n" instead of the second element of the array? I do not understand where the problem is.

+5
source share
2 answers

There is already a global name named name , it is window.name and it only accepts strings, so when you do

 var name = ["one" , "two"]; 

in a global area and you will come back

 console.log( name ); 

You are getting

 "one, two" 

and this is a type string, so name[1] is "n" , the second character in this string.
This is because you really set and get window.name , and it does not accept an array, so it runs toString() on everything you pass.

Change the variable name to something that is not yet used

+14
source

The problem is that var name is a reserved word, use names instead.

 var name = ["one" , "two"]; window.onload = function(){ document.getElementById('MinamaisVards').innerHTML=name[1]; } 

should be

 var names = ["one" , "two"]; window.onload = function(){ document.getElementById('MinamaisVards').innerHTML=names[1]; } 
+3
source

Source: https://habr.com/ru/post/1200988/


All Articles