gpt4 book ai didi

javascript - 优化数组过滤

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:54 24 4
gpt4 key购买 nike

http://jsfiddle.net/SqJ2y/

var list = [
{ mode: 1, type: 'foo', blah: 1 },
{ mode: 3, type: 'foo', blah: 1 },
{ mode: 3, type: 'foo', blah: 1 },
{ mode: 1, type: 'bar', blah: 1 },
{ mode: 2, type: 'bar', blah: 0 },
{ mode: 3, type: 'bar', blah: 1 }
];

var filter = [
{ propertyName: 'mode', value: 1 },
{ propertyName: 'type', value: 'foo' },
{ propertyName: 'blah', value: 1 }
];

var i = 0;

var result1 = $.grep(list, function(x){
i++;
return x.type === 'foo' && x.mode === 1 && x.blah === 1;
});

console.log(result1, 'iterations:', i); // 6 iterations

var j = 0;

var result2 = list;

$.each(filter, function(k, filter){
result2 = $.grep(result2, function(listItem) {
j++;
return listItem[filter.propertyName] === filter.value;
});
});

console.log(result2, 'iterations:', j); // 9 iterations

我想优化上面给出 result2 的过滤方法。

如您在 result1 中所见,可以用更少的迭代次数获得相同的结果。在我的示例中,它可能看起来不太像,但有大量列表,其中性能是一个问题。

我的问题:有什么方法可以优化 result2 的过滤,使其作为 result1 过滤?

最佳答案

您可以先构建一个匹配对象,然后重新使用它以避免循环:

var ob={};
filter.map(function(a,b){
ob[a.propertyName]=a.value;
})

result2 = $.grep(list, function(x){
j++;
return x.type === ob.tpye && x.mode === ob.mode && x.blah === ob.blah;
});


/* which has the console showing (and yes, they are the same two objects in both results):
[Object] "iterations:" 6
[Object] "iterations:" 6 */

已满:http://jsfiddle.net/SqJ2y/2/

关于javascript - 优化数组过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com