如何使用.find查看多个数组

时间:2018-03-18 01:22:19

标签: javascript jquery html

因此,在点击div时,它应该获取其data-type属性的值,并在数组中查找它。如果它不在一个地方,它会查看数组中的下一个对象。当它找到它时,它会带回整个对象。问题是我可以通过.find查看一个数组。多个怎么样?感谢。

var task1 = { name : "test", test: "nope1" }
var task2 = { name : "test", test: "nope2" }
var task3 = { name : "test", test: "nope3" }
var task4 = { name : "test", test: "nope4" }

var A = [task1, task2];
var B = [task3, task4];

$('.test').click(function(){
  var record = $(this).data('type');
  var found = /*A,*/B.find(function(t) {
    return t.test === record;
  });
  console.log(found);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" data-type="nope4">
  Nope.
</div>

1 个答案:

答案 0 :(得分:3)

您可以使用 concat 函数将多个数组连接成一个,然后执行函数 find

此示例将找到任务test: nope3

&#13;
&#13;
var task1 = {
  name: "test",
  test: "nope1"
}
var task2 = {
  name: "test",
  test: "nope2"
}
var task3 = {
  name: "test",
  test: "nope3"
}
var task4 = {
  name: "test",
  test: "nope4"
}

var A = [task1, task2];
var B = [task3, task4];

$('.test').click(function() {
  var record = $(this).data('type');
  var found = A.concat(B).find(function(t) {
    return t.test === record;
  });
  
  console.log(found);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='test' data-type='nope3'>Click me!</button>
&#13;
&#13;
&#13;