物体重复自己

时间:2013-07-11 22:48:46

标签: javascript jquery object

我正在尝试上课,学习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

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

2 个答案:

答案 0 :(得分:2)

我会尽力解释。您传递的b对象有两个属性:标题和梦想。你的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
 });

答案 1 :(得分:2)

您的代码提示两次,因为您正在遍历title对象中的每个属性(dreamb)。

这就够了:

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'
});