在“for(x in object)”循环中指定“x”的初始值
如果我有以下代码:
<html>
<body>
<script type="text/javascript">
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
var x = 1;
document.write("Value of x: " + x + "<br /><br />");
for (x in mycars)
{
document.write(x + ": " + mycars[x] + "<br />");
}
document.write("<br />Value of x: " + x + "<br />");
document.write("Number of cars: " + mycars.length);
</script>
</body>
</html>
我得到输出:
Value of x: 1
0: Saab
1: Volvo
2: BMW
Value of x: 2
Number of cars: 3
在不将 for-in 循环更改为 for 循环的情况下,是否有任何方法可以使其不显示第一个元素(“Saab”)?我希望输出是:
Value of x: 1
1: Volvo
2: BMW
Value of x: 2
Number of cars: 3
If I have the following code:
<html>
<body>
<script type="text/javascript">
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
var x = 1;
document.write("Value of x: " + x + "<br /><br />");
for (x in mycars)
{
document.write(x + ": " + mycars[x] + "<br />");
}
document.write("<br />Value of x: " + x + "<br />");
document.write("Number of cars: " + mycars.length);
</script>
</body>
</html>
I get the output:
Value of x: 1
0: Saab
1: Volvo
2: BMW
Value of x: 2
Number of cars: 3
Without changing the for-in loop to a for loop, is there any way to make it so the first element ("Saab") is not displayed? I would like the output to be:
Value of x: 1
1: Volvo
2: BMW
Value of x: 2
Number of cars: 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用
for..in
循环来循环数组。仅使用for..in
来循环对象。否则可能会产生意想不到的后果,这似乎令人困惑。使用标准的
for
循环:如果您想错过第一个项目,请将
i
最初设置为1
,而不是0< /代码>。您可能应该添加注释,这样当您回到这段代码时您就知道发生了什么。
Don't use
for..in
loops to loop through arrays. Usefor..in
only for looping through objects. Doing otherwise can have unintended consequences, that can seem baffling.Use a standard
for
loop:If you want to miss the first item out, set
i
to1
initially, rather than0
. You should probably put a comment in, so you know what's happening if you ever come back to this bit of code.无论如何,您不应该使用 for..in 循环来遍历数组。来自 MDC:
因此,您不仅不能跳过“第一个”元素,甚至不能依赖第一个元素的一致性!
You shouldn't use for..in loops to go through arrays anyway. From MDC:
So not only can you not skip the "first" element, you can't even rely on the first one being consistent!
为了达到你想要的效果,有这样的代码:
To achieve exactly what you want, have such code: