Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying array elements using JavaScript

I'm trying to display elements of a JavaScript array. Code:

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

Can anyone tell me why does it display the letter "n" instead of the second element of array? I don't understand where the problem is.

like image 755
MarisP Avatar asked Aug 23 '14 19:08

MarisP


1 Answers

There already is a global with the name name, it's window.name, and it only accepts strings, so when you do

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

in the global scope, and you get it back

console.log( name );

you get

"one, two"

and it's of type string, so name[1] is "n", the second character in that string.
This is because what you're really setting and getting is window.name, and it does not accept an array, so it runs toString() on whatever you pass it.

Change the variable name to something that isn't already in use

like image 123
adeneo Avatar answered Sep 20 '22 19:09

adeneo