for...in 循环在 JavaScript 中有用吗?

发布于 2024-12-13 20:08:05 字数 176 浏览 0 评论 0原文

我是 JavaScript 新手,目前正在学习所谓的 for...in 循环。

在 JavaScript 中编码时,人们真的会使用这些循环吗?

我可以看到所有其他类型的循环是如何有用的——但不是这个。

请有人对此进行阐明,并在可能的情况下提供一个现实生活中的示例。

I'm new to JavaScript, and I'm currently learning about the so-called for... in loop.

Does one actually use those loops when coding in JavaScript?

I can see how all other types of loops are useful — but not this one.

Someone shed some light on this please and include a real life example if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

坠似风落 2024-12-20 20:08:05

在 Javascript 中,只有 Array 对象可以使用普通的 for(;;) 循环进行迭代。 for..in 用于枚举非数组对象:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) { // if you don't want to access prototype properties
        alert(i);
        alert(obj[i]);
    }
}

In Javascript only Array objects can be iterated with a normal for(;;) loop. The for..in is used for enumeration of non-array objects:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) { // if you don't want to access prototype properties
        alert(i);
        alert(obj[i]);
    }
}
这样的小城市 2024-12-20 20:08:05

它通常用于循环某些内容的集合。例如,由于每个 JavaScript 对象都可以视为属性的集合,因此您可以通过这种方式枚举属性。

//let's loop throug all properties of a "document" 
//we don't know what these will be
var txtProps = "";
for (var prop in window.document) {
   txtProps += prop + "\n";
}
alert(txtProps);//pops out a message showing a looong list of all properties

It is typically used to loop over a collection of something. For instance, since every JavaScript object can be treated as a collection of properties, you can enumerate properties in this manner.

//let's loop throug all properties of a "document" 
//we don't know what these will be
var txtProps = "";
for (var prop in window.document) {
   txtProps += prop + "\n";
}
alert(txtProps);//pops out a message showing a looong list of all properties
笑着哭最痛 2024-12-20 20:08:05

我认为只要您了解对象可以容纳的不仅仅是简单的变量,就可以了。考虑这个从 w3schools.com 修改的示例来说明这一点:

<script type="text/javascript">

//This is probably as you expect:
var person={fname:"John",lname:"Doe",age:25}; 

//This is probably unexpected and unwanted, but is valid and will be an output of the for...in loop:
person.f = function(){
 alert("Hi");
};

//Use typeof() function to check that the data type is what you expect:
for (x in person){
   document.write(typeof(person[x]) + " ");
}

</script>

打印:

string string number function

为了回答有关循环类型之间差异的具体问题,for() 循环非常适合具有 length 属性的数组类型。 foreach() 循环可以很好地用于迭代对象集合,而 foreach ...in 循环可以很好地用于对象的键(不声称这些是任何循环类型的独占用途)。

I think it's OK so long as you understand that an object can hold more than simple variables. Consider this example, modified from w3schools.com to illustrate the point:

<script type="text/javascript">

//This is probably as you expect:
var person={fname:"John",lname:"Doe",age:25}; 

//This is probably unexpected and unwanted, but is valid and will be an output of the for...in loop:
person.f = function(){
 alert("Hi");
};

//Use typeof() function to check that the data type is what you expect:
for (x in person){
   document.write(typeof(person[x]) + " ");
}

</script>

This prints:

string string number function

To answer your specific question about the differences between loop types, the for() loop works well for array types with a length property. The foreach() loop can work well for iterating over collections of objects, while the foreach ...in loop works well for keys of an object (Not claiming that these are exclusive uses for any of the loop types).

北笙凉宸 2024-12-20 20:08:05

要理解这一点,您首先需要了解 JavaScript 的对象模型。

正如您所注意到的,在处理数组时,for...in 循环并不是那么有用,因为 for (;;) 循环更容易完成这项工作。

但数组只是一种具有数字属性的 JavaScript 对象,而 for (;;) 循环仅处理数字属性。使用 myArray[0] 表示法的原因是您可以对任何属性名称使用此方括号表示法。因此 myObject['myProperty']myObject.myProperty 相同。这就是 for...in 变得有用的地方:

for (var i in myObject) {
    alert(myObject[i]);
}

因此,如果我们设置的唯一属性是 myProperty,那么 i 将等于 >“myProperty”(请注意,它是一个字符串,这使其比仅仅作为变量名称更加动态)。

但这里有一个巨大的“但是”。对象有一个叫做原型的东西,这些原型有自己的属性和方法。如果我执行以下操作:

for (var i in myArray) {
    alert(i + ': ' + myArray[i]);
}

...我不仅会收到数值(1、2、3 等)的警报,还会收到数组属性的警报,例如 length,及其方法,例如 join。这些属性实际上属于 Array 对象的原型,并且可以通过执行以下操作来过滤原型属性:

for (var i in myArray) {
    if (myArray.hasOwnProperty(i)) {
        alert(i + ': ' + myArray[i]);
    }
}

现在我将再次收到数值警报,这意味着这(几乎)与 for 完全相同(var i = 0;; i < myArray.length; i++)。当我们可以使用该符号时,为什么我要告诉你这个?因为所有对象都有原型,而不仅仅是数组。每个对象都源自 Object 对象,因此如果有人定义了 Object.prototype.myProperty = "some string value" 那么它总是会出现在任何 for 中...in 循环,用于页面的其余部分。值得庆幸的是,hasOwnProperty 方法本身属于 Object.prototype,因此您可以(并且应该)始终在 for...in 中使用它循环。

所以这是一个成熟的 for...in 示例:

// This is just one way of defining an object. We could also use a constructor function, or `new Object()`
var myObject = {
    aProperty : "my first property value",
    anotherProperty : "second property value"
    4 : "numeric property names work too, you know"
}

for (var i in myObject) {
    if (myObject.hasOwnProperty(i)) {
       document.write(i + ': ' + myObject[i] + '<br />\n'); 
    }
}

输出:

aProperty: my first property value
anotherProperty: secondPropertyValue
4: numeric property names work too, you know

希望这能解释一切。

To understand this, you first need to understand JavaScript's object model.

As you'll have noted, when working with arrays, for...in loops aren't that useful because for (;;) loops do the job more easily.

But arrays are just a type of JavaScript object with numeric properties, and for (;;) loops only handle numeric properties. The reason for the notation myArray[0] is that you can use this square bracket notation for any property name. So myObject['myProperty'] is the same as myObject.myProperty. This is where for...in becomes useful:

for (var i in myObject) {
    alert(myObject[i]);
}

So if the only property we'd set was myProperty, then i would equal "myProperty" (note that it's a string, which makes it more dynamic than just being a variable name).

There's a huge BUT here though. Objects have something called a prototype, and these prototypes have their own properties and methods. If I do the following:

for (var i in myArray) {
    alert(i + ': ' + myArray[i]);
}

...I won't just get alerted with numeric values (1, 2, 3, etc.) I'll also get alerted with the array's properties such as length, and its methods such as join. These properties actually belong to the Array object's prototype, and the prototype properties can be filtered out by doing the following:

for (var i in myArray) {
    if (myArray.hasOwnProperty(i)) {
        alert(i + ': ' + myArray[i]);
    }
}

Now I'll just get alerted with numeric values again, which means this is (almost) exactly the same as for (var i = 0;; i < myArray.length; i++). Why am I telling you this when we can just use that notation? Because all objects have prototypes, not just arrays. And every object descends from the Object object, so if somebody defined Object.prototype.myProperty = "some string value" then that would always show up in any for...in loop you use in the rest of the page. Thankfully, the hasOwnProperty method itself belongs to Object.prototype, so you can (and should) always use it in your for...in loops.

So here's a fully fledged for...in example:

// This is just one way of defining an object. We could also use a constructor function, or `new Object()`
var myObject = {
    aProperty : "my first property value",
    anotherProperty : "second property value"
    4 : "numeric property names work too, you know"
}

for (var i in myObject) {
    if (myObject.hasOwnProperty(i)) {
       document.write(i + ': ' + myObject[i] + '<br />\n'); 
    }
}

Output:

aProperty: my first property value
anotherProperty: secondPropertyValue
4: numeric property names work too, you know

Hopefully this explains it all.

手心的海 2024-12-20 20:08:05

for infor 都有特定的用途。让我们看一些。

如果你有一个对象

var obj = { one: 1, two: 2 }; 

,那么你可以使用for in循环迭代它的属性,即

for( var i in obj ) console.log( obj[i] );  //use obj.hasOwnProperty(i) to exclude prototype properties 

注意,如果你尝试通过for迭代obj循环它不会工作,因为它会使用数字索引来访问键并且会给出一个未定义的,即 obj[0] 将会是未定义的。这与获取对象的长度比简单地编写 obj.length 更复杂这一事实无关。当然,如果您有数字属性,您将能够使用 for 循环,for in 只是更自然地适合对象迭代。

如果您有一个数组

 var array = [1,2] 

从技术上讲您可以同时使用这两个,建议您为此使用 for 循环。这就是为什么

  1. 不能保证元素顺序。
  2. 原型属性也将被迭代,这可能会导致不必要的副作用。

为了说明第二点,让我们扩展 Array。

Array.prototype.print_array = function(){ console.log(this) }; 

我们刚刚添加到 Array 的这个函数将被所有 Array 对象继承,因此,通过 for in 迭代数组

for( var i in array ) console.log( array[i] ); 

会产生收益

1
2
function (){ console.log(this) } // the prototype property was iterated over also

,并且使用 for 迭代数组

for( var i =0; i < array.length; i++) console.log( array[i] ); 

将产生预期的结果。

1
2

因此,对于对象迭代,请使用 for in;对于数组迭代,请使用 for

Both for in and for serve specific purposes. Let's look at some.

If you have an object

var obj = { one: 1, two: 2 }; 

Then you can iterate over it's properties using the for in loop i.e

for( var i in obj ) console.log( obj[i] );  //use obj.hasOwnProperty(i) to exclude prototype properties 

note, if you try to iterate obj via a for loop it wouldn't work because it would use numeric indexes to access the keys and would give an undefined i.e obj[0] would be undefined. This is aside form the fact that getting the length of an object would be more involved than simply writing obj.length. Of course if you had numeric properties you would be able to use the for loop, for in is just a more natural fit for object iteration.

If you have an array

 var array = [1,2] 

you could technically use both but it's recommended that you use the for loop for this. Here's why

  1. The element order is not guaranteed.
  2. Prototype properties will also be iterated over, which could cause unwanted side effects.

To illustrate point two, let's extend Array.

Array.prototype.print_array = function(){ console.log(this) }; 

This function that we just added to Array will be inherited by all Array objects, hence, iterating over the array via a for in

for( var i in array ) console.log( array[i] ); 

Would yield

1
2
function (){ console.log(this) } // the prototype property was iterated over also

And iterating over the array with the for

for( var i =0; i < array.length; i++) console.log( array[i] ); 

would yield the expected result.

1
2

Hence, for object iteration use the for in and for array iteration use the for

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文