【问题标题】:Using Javascript's filter function使用 Javascript 的过滤功能
【发布时间】:2014-09-09 12:54:55
【问题描述】:

我会尽我所能正确地表达这一点 - 感谢您的帮助。

我有一个数组,其中包含一系列邮政编码,(例如六个)其中一个将为空。使用 javascripts 过滤功能,我使用以下代码删除了为空的元素:

var filteredrad = radius1.filter(function(val) {
  return !(val === "" || typeof val == "undefined" || val === null);
});

现在我需要以某种方式存储从原始数组中删除的元素的索引,但我不确定如何去做。

例如,过滤器将删除索引 1 处的空间。如何保存该第一个以供以后使用?

["WC1A 1EA", "", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"] 

希望这是有道理的,任何帮助将不胜感激。

阿什利

【问题讨论】:

  • 尝试添加第二个参数:radius1.filter(function(val, index)

标签: javascript arrays filter


【解决方案1】:

你可以使用副作用,使用filtersecond argument

var removed = [];
var filteredrad = radius1.filter(function(val, index) {
    if (val === "" || typeof val == "undefined" || val === null) {
        removed.push(index);
        return false;
    }
    return true;
});

【讨论】:

  • 感谢 Jean,正是我所追求的!计时器到期后将立即接受。
【解决方案2】:

过滤器函数将三个参数传递给回调函数https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

所以你可以写:

var storedIndexes = []
var filteredrad = radius1.filter(function(val, index) {
  val isNull = (val === "" || typeof val == "undefined" || val === null);
  if(isNull){
    storedIndexes.push(index);
  }
  return !isNull;
});

并将索引保​​存在storedIndexes中

【讨论】:

    【解决方案3】:
    radius1 = ["WC1A 1EA", "", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"];
    removed = [];
    var filteredrad = radius1.filter(function(val, index) {
      if (val === "" || typeof val == "undefined" || val === null) {
        removed.push(index); 
        return false;
      }
      return true;
    });
    

    【讨论】:

    • 我认为,当您为您的意图添加一些解释时,这对 OP 和进一步的访问会更有帮助。
    【解决方案4】:

    只是另一个以另一种方式做你想做的事的例子

    var collection = ["WC1A 1EA", "", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"] ;
    
    var postalCodes = (function(){
      var emptyIndices;
    
      return {
        getCodes: function( array ){
          emptyIndices = [];
          return array.filter(function( value, index, array ){
            if( !value ){
              emptyIndices.push(index);
              return false;
            }else{
              return true;
            }
          });
        },
        getEmptyIdices: function(){
          return emptyIndices || null;
        }
      };
    })();
    

    然后打电话

    postalCodes.getCodes(collection);
    => ["WC1A 1EA", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"];
    
    postalCodes.getEmptyIndices();
    => [1];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      相关资源
      最近更新 更多