下划线等效于 Javascript For Loop



我想转换这段代码:

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

下划线.js请帮忙。

解决此问题的另一种方法是首先使用underscore的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(product.ages, age => scope_ages[age.id].ticked = true)   

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

这将是您在下划线中的代码:

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

下面是一个关于如何在对象上执行 _.each 的示例。

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

您可以使用

_.find

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

另外,只是一个指针,您应该在匹配时使用break

最新更新