【问题标题】:if statement in jQuery each. loop of arrayjQuery 中的 if 语句。数组循环
【发布时间】:2012-09-20 14:38:54
【问题描述】:

我有这个数组

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.

提前致谢!

【问题讨论】:

    标签: jquery arrays match


    【解决方案1】:

    试试:

    $.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"];
    

    【讨论】:

    • 感谢您提供简单的解决方案!我正在从中赚到更多,然后我需要!
    【解决方案2】:

    这将更新 bmpArray:

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

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

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

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

    【讨论】:

      【解决方案3】:

      如果你想要的话:

      ["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"]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多