gpt4 book ai didi

Javascript for 循环

转载 作者:行者123 更新时间:2023-11-29 17:06:10 25 4
gpt4 key购买 nike

var myArray = new Array();
var increment = 0;

myArray.push('Tom Hanks', 'Pierce Brosnan', 'Will Smith', 'Richard Ayoade');

for (actor in myArray) {
console.log(actor + ' is my #' + increment + ' choice.');
increment++;
}

这个 for 循环有问题,我相信它在 for-in 循环中的“ Actor ”。这将打印出 Actor 姓名所在的数字。

来自 Ruby,这看起来像一个 .each 方法迭代数组中的每个元素,但显然这有点不同。谁能解释为什么这不起作用?

今天刚学了 JS。谢谢。

最佳答案

Thats not how for ... in works.从该链接:

A for...in loop iterates over the properties of an object in an arbitrary order

和:

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

鉴于您要传入一个数组,属性是它包含的项目的索引。

这就是您获取索引而不是名称的原因。

如果你想保留顺序并打印名字,你需要一个“传统的”for 循环,像这样:

for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i] + ' is my #' + (i+1) + ' choice.');
}

使用 for .. in 时要小心的原因是它可能会产生意想不到的结果。 查看此 jsFiddle ...

var myArray = new Array();
var increment = 0;

myArray.push('Tom Hanks', 'Pierce Brosnan');
myArray.hello = "what?";

for (actor in myArray) {
alert(actor + ' is my #' + increment + ' choice.');
increment++;
}

for (var i = 0; i < myArray.length; i++) {
alert(myArray[i] + ' is my #' + (i+1) + ' choice.');
}

在此示例中,第一个循环将迭代 3 次,选取“hello”属性以及数组中的其余属性。而第二个只处理数组中的 2 正式项。

关于Javascript for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com