对于..在循环? [英] For .. in loop?

查看:190
本文介绍了对于..在循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里失去了..我现在非常困惑这个循环是如何工作的。



从w3学校:

  var person = {fname:约翰,L-NAME: 李四,年龄:25}; 

(x in person)
{
document.write(person [x] +); b





$ b

person是一个有属性的对象吗?这些属性如何用括号访问?我认为这是数组?



为什么这也工作,不应该只是这样?:

  var person = []; 
person [fname] =John;
person [lname] =Doe;
person [age] =25;


for(x person)
{
document.write(person [x] +);


解决方案

有两种方法你可以访问一个对象的属性:


  • obj.key

  • obj ['key']



第二种方法的优点是你也可以动态地提供密钥,例如在你的例子中 obj [x] obj.x 字面意思是 x 属性(即 obj ['x'] ),这不是你想要的。



数组只能使用括号,但括号不限于数组。数组也在对象之下,但为数字键设计。你可以使用非数字键添加属性,但这不是他们设计的。


I'm losing it here.. I am now extremely confused about how this loop works.

From w3 schools:

var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
{
document.write(person[x] + " ");
}

person is an object with properties right? How are those properties being accessed with the brackets? I thought that was for arrays?

Why does this also work, and shouldn't it ONLY be like this?:

var person=[]; 
person["fname"] = "John";
person["lname"] = "Doe";
person["age"] = "25";


for (x in person)
{
document.write(person[x] + " ");
}

解决方案

There are two ways in which you have access to an object's properties:

  • obj.key
  • obj['key']

The advantage of the second method is that you can also provide the key dynamically, e.g. obj[x] in your example. obj.x would literally mean the x property (i.e. obj['x']), which is not what you want.

Arrays only work with brackets, but brackets are not limited to arrays. Arrays are under the hood also objects, but designed for numeric keys. You can still add properties with non-numeric keys to them, but that's not what they are designed for.

这篇关于对于..在循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆