我有一个数组,看起来像:
var testArr = ["40", "A1", "B9", "58"]
我想遍历某个类的所有 div 元素,并只返回数据属性与该数组中的任何项目匹配的元素。
如果我这样做:
$("div.prodCodes").filter(function(e) {
var x1 = $(this);
var x2 = $(this).data("prodCode");
testArr.forEach(function(e) { if (e == x2) { console.log("MATCH"); } });
});
该控制台输出正确数量的匹配项,但我无法return过滤函数中的那些元素。
我到底想念什么?我试过创建一个新数组并将每个项目推到它上面并返回that,但它总是空的。我确定我在这里遗漏了一些明显的东西。我也尝试过使用 .grep() 重写它并且无处可去。感谢帮助。
您需要在
filter()
中返回一个真值才能包含一个项目。
尝试:
$("div.prodCodes").filter(function(e) {
return testArr.indexOf($(this).attr('data-prodCode')) >-1;
}).doSomething();
没有
return
所有项目都将被排除
我会使用
Set
进行恒定时间查找。
注意 jQuery 在使用
data
方法时将属性值“58”读取为数字,因此除非您确保数据类型相同,否则它不会匹配:
// Use a set
var testSet = new Set(["40", "A1", "B9", "58"]);
var texts = $("div.prodCodes").filter(function() {
var x = $(this).data("prodCode").toString(); // data type must match
// Return a boolean to indicate whether the div element should be kept
return testSet.has(x); // Set#has() is fast
}).map(function(){
// For demo only: get the text content of the matching div elements
return $(this).text();
}).get(); // convert that to a plain array
console.log(texts);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="prodCodes" data-prod-code="A1">Hello</div>
<div class="prodCodes" data-prod-code="XX">Not this one</div>
<div class="prodCodes" data-prod-code="58">There</div>
const elements = ['apple', 'banana', 'orange'];
const objects = [
{ id: 1, fruit: 'apple' },
{ id: 2, fruit: 'pear' },
{ id: 3, fruit: 'orange' },
{ id: 4, fruit: 'banana' }
];
const results = objects.filter(obj => elements.includes(obj.fruit));
console.log(results);