javascript简单循环

时间:2015-04-23 12:33:57

标签: javascript for-loop

var friends = ["Miha", "Artur", "Karen", "zollex"];
var len = friends.length;
var friend = 0;
var msg = '';
var i;
for (i = 0; i <len; i++){ 
  friend = (i + 1);
  msg+= "Friend number " + friend + ":";
  msg+=friends[i] + "<br />";
  document.write(msg);
}

我上面写的代码如下。结果如下:

朋友1:Miha
朋友1:Miha
朋友2:阿图尔 朋友1:Miha
朋友2:阿图尔 朋友3:凯伦
朋友1:Miha
朋友2:阿图尔 朋友3:凯伦
朋友4:zollex

虽然应该只有4个朋友。我真的好奇为什么document.write多次重复同名。

2 个答案:

答案 0 :(得分:6)

因为您在每次迭代时使用+ =构建字符串,并且您不会在每次迭代时重置它。

msg += "Friend number " + friend + ":";
    ^^
msg += friends[i] + "<br />";
    ^^

document.write移出for循环或在每次迭代时将msg设置为空。

var friends = ["Miha", "Artur", "Karen", "zollex"];
var len = friends.length;
var friend = 0;
var msg = '';
var i;
for (i = 0; i <len; i++){ 
  friend = (i + 1);
  msg += "Friend number " + friend + ":";
  msg += friends[i] + "<br />";
}
document.write(msg);

答案 1 :(得分:2)

for (i = 0; i <len; i++){ 
  msg = '';
  friend = (i + 1);
  msg+= "Friend number " + friend + ":";
  msg+=friends[i] + "<br />";
  document.write(msg);
}

你正在覆盖每个循环上的msg变量,而你应该在每个循环上清除它!