JavaScript:如何动态地“过滤"我的对象 [英] JavaScript: How do I dynamically "filter" my objects
问题描述
如何使用JavaScript"filter
"属性过滤我的JavaScript对象?
How do I user the JavaScript "filter
" attribute as filter my JavaScript object?
我一直在阅读以下 StackOverflow发布,并且处于类似情况.
I've been reading the following StackOverflow post, and am in a similar situation.
我有以下JavaScript对象:
I have the following JavaScript object:
{
'cars' :
[{
"car_id" : "1",
"price" : "42999",
"make_id" : "050",
"year_built" : "2007",
"color_id" : "832"
},
..........
]}
我正在使用JQuery来显示控件,使人们可以根据以下条件进行过滤:价格,品牌,年份,颜色
I'm using JQuery to display controls to allow people to filter based on: Price, Make, Year Built, Color
根据其他帖子,我可以使用以下代码:
Per that other post, I can use the following code:
// if using an old browser, define the 'filter' attribute
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
然后执行实际的过滤,我可以这样做:
then to perform the actual filter, I can do:
result = cars.
filter(function(p) { return p.price >= 15000 }).
filter(function(p) { return p.price <= 40000 }).
filter(function(p) { return p.year_built >= 2000 }) etc
我不了解的是,一旦设置了过滤器,如何使用我的JQuery控件动态更改filter
?意思是说我从上面的 then 用户改变了主意,并希望将他们愿意为汽车支付的最高费用从40,000美元提高到50,000美元.
What I don't understand is, how do I use my JQuery controls to dynamically change the filter
once the filter has already been set? Meaning, let's say I have the filter applied from above, then the user changes there mind and wants to increase the maximum they are willing to pay for a car from $40,000 to $50,000.
我如何从以下位置麻烦地修改我的过滤器:
How would I problematically modify my filter from :
filter(function(p) { return p.price <= 40000 }).
收件人:
filter(function(p) { return p.price <= 50000 }).
推荐答案
一旦设置了过滤器,如何使用我的JQuery控件动态更改过滤器?
how do I use my JQuery controls to dynamically change the filter once the filter has already been set?
您没有设置过滤器.您可以使用过滤器函数调用filter()
并返回过滤后的数组;您将无法更改之后应用于数组的过滤器.相反,您必须再次调用filter()
,并传递一个不同的过滤器功能.
You don't set a filter. You call filter()
with a filter function and get a filtered array back; you can't change the filter that was applied to the array afterwards. Instead you must call filter()
again, and pass a different filter function.
或者是相同的过滤器函数,其关闭了已更改的变量:
Or the same filter function with a closure over a variable that has changed:
var minprice= 10000;
var minpricefilter= function(p) { return p.price>=minprice };
result= cars.filter(minpricefilter);
minprice= 20000;
result= cars.filter(minpricefilter);
这篇关于JavaScript:如何动态地“过滤"我的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!