[英]A javascript filter using a for/in loop?
Is it possible to filter a javascript array? 是否可以过滤JavaScript数组? I've taken the following approach but it doesn't seem to produce the intended results. 我采用了以下方法,但似乎无法产生预期的结果。
Arrays: 阵列:
var catalog1 = [0]
var catalog2 = [1]
var products = [{ id: "PRODUCTA", desc: "Toys" },
{ id: "PRODUCTB", desc: "Cars" }]
Filter: 过滤:
var NewProducts = [];
for (r in catalog1) NewProducts.push(products[r]);
NewProducts
should contain either product A or B depending on which catalog array is selected. NewProducts
应包含产品A或B,具体取决于选择的目录阵列。 My attempt always return product A, as in r = 0. What am I missing? 我的尝试总是返回乘积A,如r =0。我缺少什么?
It is because Javascript's for each loop generates the keys of your collection. 这是因为每个循环的Javascript都会生成您集合的键。 You will have to change it to: 您将不得不将其更改为:
for (var r in someCatalogue) NewProducts.push(products[someCatalogue[r]]);
You can also use map inside a closure, if you don't have to support IE8 and less: 如果不必支持IE8及以下版本,也可以在闭包内使用map:
(function(products) {
NewProducts = someCatalogue.map(function(item) { return products[item]; });
})(products);
It is possible to filter a JavaScript array, just use the filter
method: 可以过滤JavaScript数组,只需使用filter
方法:
var arr = [1, 2, 3, 4, 5, 6];
var result = arr.filter(function(item) {
return item > 3;
}
);
In your situation you are trying to filter the products
array to include certain elements, so to do it the right way: 在您的情况下,您尝试过滤products
数组以包含某些元素,因此以正确的方式进行操作:
var catalog1 = [0];
var catalog2 = [1];
var products = [{ id: "PRODUCTA", desc: "Toys" },
{ id: "PRODUCTB", desc: "Cars" }];
var NewProducts = products.filter( function(item) {
// check item and if it is accepted then include it.
}
);
In your code, you are using for/in to loop the array elements which is not the right way to walk the array, use a regular for loop: 在您的代码中,您使用for / in循环数组元素,这不是遍历数组的正确方法,请使用常规的for循环:
var NewProducts = [];
for (var i=0; i<catalog1.length; i++) NewProducts.push(products[catalog1[i]]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.