为什么javascript for循环只打印最后一个元素

时间:2013-10-16 10:57:44

标签: javascript

我正在测试javascript for循环。

var items = ['one','two','three']
for(var i=0, l=items.length; i < l; i++){
    console.log(i);
    items[i];
}

输出如下。

0
1
2
"three"

为什么只有最后一项才被打印出来,如果它没有包含在console.log中?

EDIT1:我为最初的复制粘贴搞砸而道歉。我更新了代码。如果我打印项目[i]作为控制台日志的一部分,它会打印所有三个项目,但不打印在外面。

1 个答案:

答案 0 :(得分:4)

你的循环本身没什么问题。你错了的是,将"three"视为输出。

"Three"只是此表达式的最后一个值。

如果你要写

var items = ['one','two','three'];
for(var i=0; i < items.length; i++){
    i; // i itself just calls the variable and does nothing with it. 
       // Test it with the developer console on Google Chrome and you'll notice a
       // different prefix before the line
}

没有输出,因为只有console.log()生成实际输出。如果你想输出i和数组中的值,你的代码将是:

var items = ['one','two','three'];
for(var i=0; i < items.length; i++){
    console.log(i);
    console.log(items[i]);
}
相关问题