最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Displaying array elements using JavaScript - Stack Overflow

programmeradmin10浏览0评论

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.

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.

Share Improve this question asked Aug 23, 2014 at 19:46 MarisPMarisP 9872 gold badges10 silver badges27 bronze badges 1
  • 2 It looks like there is some other code that is being run that is changing name before the window.onload event is being fired. – Tom Fenech Commented Aug 23, 2014 at 19:50
Add a comment  | 

2 Answers 2

Reset to default 14

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

The problem is in var name as its 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];
}
发布评论

评论列表(0)

  1. 暂无评论