2017-07-25 120 views
0

/*枚举为什么我会得到不同的结果?使用name.property和name [property]

for in语句可以遍历对象中的所有属性名称。枚举将包含函数和原型属性。 */

//第一个代码我写

var fruit = { 
    apple: 2, 
    orange: 5, 
    pear:1 
}, 
sentence = 'I have', 
quantity; 
for (kind in fruit) { 
    quantity = fruit[kind]; 
    sentence += quantity + '' + kind + 
       (quantity === 1?'': 's') + 
       ', '; 
} 
sentence = sentence.substr(0,sentence.length-2) + '.'; 
alert(sentence); 

//第二个代码我写

var fruit = { 
    apple: 2, 
    orange: 5, 
    pear:1 
}, 
sentence = 'I have', 
quantity;// 
for (kind in fruit) { 
    quantity = fruit.kind; 
    sentence += quantity + '' + kind + 
       (quantity === 1?'': 's') + 
       ', '; 
} 
sentence = sentence.substr(0,sentence.length-2) + '.'; 
alert(sentence); 
+0

因为fruit.kind等于水果。['kind']。你的第二个例子中没有评价类。 – Bellian

+0

语法错误:'fruit。['kind']'实际上应该是'fruit ['kind']' –

回答

0

那是因为你kind是一个变量。

当你写fruit.kind,JS引擎实际上将其解释为fruit['kind']

1

这个问题的根源是访问属性之间的点(obj.prop)对数组符号(差OBJ [丙])。

  • obj.prop手段访问名为属性“托”这是从OBJ对象访问。
  • OBJ [丙]另一方面装置:确定所述变量的字符串值和访问属性匹配OBJ对象上的字符串值。

在第一种情况:

for (kind in fruit) { 
    quantity = fruit[kind]; 
} 

变量获得分配字符串 “苹果”, “橙”, “梨” 的for循环执行过程中。所以你可以像这样的水果[“苹果”](相当于fruit.apple),水果[“orange”](或fruit.orange)和水果[“pear”]或(fruit.pear )。

在第二种情况:

for (kind in fruit) { 
    quantity = fruit.kind; 
    ... 
} 

你总是访问水果对象的那种财产。由于水果对象不具有属性,您将永远得到undefined

如果你想了解更多关于如何解决JavaScript中的财产访问问题,你可以看看Secrets of the JavaScript Ninja本书 - 它帮助了我。

相关问题