未捕获的TypeError:无法读取未定义的属性“0”

时间:2013-12-10 05:55:28

标签: javascript

var names = ["andy","amy","randy","ronaldo","nani"];

for(var i = 0;i<names.length;i++){
    console.log("My name is " . names[i]);
}

我想知道这里有什么问题。为什么我不能为零?

3 个答案:

答案 0 :(得分:4)

JavaScript不是PHP,此处的字符串连接是通过+进行的,而不是.

var names = ["andy","amy","randy","ronaldo","nani"];

for(var i = 0;i<names.length;i++){
    console.log("My name is " + names[i]);
}

答案 1 :(得分:1)

错误是因为

中的.
console.log("My name is " . names[i]);

将此更改为逗号(,)或加号(+

console.log("My name is ", names[i]);
console.log("My name is " + names[i]);

答案 2 :(得分:0)

我认为您将javascript串联与php

混淆了

var names = [“andy”,“amy”,“randy”,“ronaldo”,“nani”];

for(var i in names){
    console.log("My name is " + names[i]); // change . with + here
}

您也可以使用var i in names

最小化循环

检查此http://jsfiddle.net/g96T8/