下划线相当于Javascript For Loop?

时间:2016-07-10 04:47:53

标签: javascript underscore.js

我想转换此代码:

for (var i = 0; i < product.ages.length; i ++){
    for (var j = 0; j < $scope.ages.length; j ++){
        if (product.ages[i].id == $scope.ages[j].id){
            $scope.ages[j]['ticked'] = true;
        }
    }
}

进入underscore.js。请帮忙。

4 个答案:

答案 0 :(得分:1)

这将是您的下划线代码:

_.each(product.ages, function(pAge) {
  _.each($scope.ages, function(sAge) {
    if (pAge.id === sAge.id) {
      sAge.ticked = true;
    }
  });
});

答案 1 :(得分:1)

解决此问题的另一种方法是首先使用下划线indexBy创建scope.ages的哈希:

var scope_ages = _.indexBy($scope.ages, 'id');

该对象看起来像:

{
    1: ref to scope.ages with id 1,
    2: ref to scope.ages with id 2,
    etc.
}

然后使用each迭代产品年龄以设置勾选的值:

_.each(product.ages, age => scope_ages[age.id].ticked = true)   

&#13;
&#13;
var product = {
	ages: [
		{ id : 1 }
	]
}

var $scope = {
	ages: [
		{ id : 0, ticked: false },
		{ id : 1, ticked: false },
		{ id : 2, ticked: false },
	]
}

var scope_ages = _.indexBy($scope.ages, 'id');

_.each(product.ages, age => scope_ages[age.id].ticked = true)

document.getElementById('scope_ages').textContent = JSON.stringify(scope_ages);
document.getElementById('result').textContent = JSON.stringify($scope.ages);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<h1>scope_ages</h1>
<p>
    <pre id="scope_ages"></pre>
</p>
<h1>Scope</h1>
<p>
  <pre id="result"></pre>
</p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

以下是关于如何对对象执行_.each的示例。

var example = {"hello":"world", "this":"is", "super":"neat"};
_.each(example, function(value, index){
  console.log(index + ":" + value);
}
->hello:world
->this:is
->super:neat

答案 3 :(得分:0)

您可以使用_.find

_.each($scope.ages, function(v){
  v.ticked = _.find(product.ages, function(a){
    return v.age === a.age;
  })?true:false;
})

另外,只需一个指针,就可以在匹配时使用break