0

我有这个数组

var bmpArrayNames=["strip_cropping", "crop_rotation", "cover_crops", "filter_strips", "grassed_waterway", "conservation_tillage", "binary_wetlands"];

和这个数组

var bmpArray=["1", "1", "0", "0", "0", "0", "0"];

我需要遍历这个 bmpArray 来查看值是否 =1。如果是这样,我想用 bmpArrayNames 的同一索引处的值替换该值。然后我会删除所有最终以 bmpArray=["strip_cropping,"crop_rotation"] 结尾的“0”

我从这个开始但没有被卡住

$.each(bmpArray, function(index, value) { 
if (value=="1")
//so if i find a match how do I replace with the same indexed value in the other array.

提前致谢!

4

3 回答 3

2

尝试:

$.each(bmpArray, function(index, value) {
    if (value == "1") {
        bmpArray[index] = bmpArrayNames[index];
    }
});

$.grep(bmpArray, function(item, index) {
    return bmpArray[index] != "0";
});

输入:

var bmpArrayNames = ["strip_cropping", 
                     "crop_rotation", 
                     "cover_crops",
                     "filter_strips", 
                     "grassed_waterway", 
                     "conservation_tillage", 
                     "binary_wetlands"];

var bmpArray = ["1", "1", "0", "0", "0", "0", "0"];

输出:

bmpArray : ["strip_cropping", "crop_rotation"];
于 2012-09-20T14:41:29.887 回答
2

这将更新 bmpArray:

$.each(bmpArray, function(index, value) { 
    if (value==="1"){
        bmpArray[index] = bmpArrayNames[index];
    }
});

请注意,鼓励使用三等号运算符,以防止意外的类型强制。

要删除零,您可以使用该grep函数,如下所示:

bmpArray = $.grep(bmpArray, function(item){
    return item !== "0";
});
于 2012-09-20T14:42:26.100 回答
2

如果它是你想要的:

["strip_cropping", "crop_rotation"]

作为最终结果,您可以使用 jQuery .grep 方法:

var bmpArrayNames = ["strip_cropping", "crop_rotation", "cover_crops", "filter_strips", "grassed_waterway", "conservation_tillage", "binary_wetlands"];
var bmpArray = ["1", "1", "0", "0", "0", "0", "0"];

bmpArrayNames = jQuery.grep( bmpArrayNames, function(item, index) {
    return bmpArray[index] == "1";
});

bmpArrayNames现在将是["strip_cropping", "crop_rotation"]

于 2012-09-20T14:51:19.957 回答