0

我正在尝试上课,学习javascript对象等等......我在循环中遇到了这个问题,我想对象文字本身

var darkness = { 
  add: function(a,b) {
  for(var title in b) {
      alert(a+ " is the "+ b.title );
      alert(a+ " holds many of"+b.dream);
    }
  }
};


darkness.add('darkness',{
  title :'feelings',
  dream:'dreams'
 });

这会提示两次?测试http://jsbin.com/ogunor/1/edit

有人可以帮我更好地学习这些吗

4

2 回答 2

2

我会尽力解释。你传递的b对象有两个属性:title 和dream。您的for(var title in b)循环将遍历每个对象属性键..意思将运行两次-第一次迭代将具有title = 'title',第二次将具有title='dream'. 在每次迭代中,您会发出两次警报 - 因此会收到 4 次警报。您可以完全删除循环,仅保留警报以使其仅发出两次警报。

var darkness = { 
  add: function(a,b) {
  for(var title in b) { // runs twice cuz you have 2 properties
      alert(title); // try alerting title just to see what it hold in each iteration.
      alert(a+ " is the "+ b.title );
      alert(a+ " holds many of"+b.dream);
    }
  }
};


darkness.add('darkness',{
  title :'feelings', // 1st property
  dream:'dreams' // 2nd property
 });
于 2013-07-11T22:56:20.027 回答
2

您的代码会发出两次警报,因为您正在遍历对象中的每个属性(titledreamb

这就够了:

var darkness = { 
    add: function(a,b) {
        alert(a+ " is the "+ b.title );
        alert(a+ " holds man of " +b.dream);
    }  
};

darkness.add('darkness',{
  title :'feelings',
  dream:'dreams'
});
于 2013-07-11T22:56:45.313 回答