从数组中删除空字符串,同时保持记录无循环?

Uni*_*asp 84 javascript arrays string indexing removeall

这里提出了这个问题: 从数组中删除空字符串,同时保留非空字符串索引的记录

如果你注意到@Baz给出的那个;

"I", "am", "", "still", "here", "", "man"
Run Code Online (Sandbox Code Playgroud)

"并且由此我希望生成以下两个数组:"

"I", "am", "still", "here", "man"
Run Code Online (Sandbox Code Playgroud)

这个问题的所有答案都提到了一种循环形式.

我的问题:是否有可能在没有任何循环的情况下删除所有indexes empty string ...除了迭代数组之外还有其他选择吗?

可能是我们不知道的一些regex或一些jQuery

所有答案或建议都非常感谢.

Isa*_*aac 304

var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]
Run Code Online (Sandbox Code Playgroud)

filter 文件


// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]
Run Code Online (Sandbox Code Playgroud)

箭头功能文档

  • @DiegoPlentz仍在运行IE8的人会遇到更多的问题,而不仅仅是删除阵列中的空白......这几天我几乎没有考虑过支持这种浏览器 (14认同)
  • 我确切地知道你的感受,我几个月前用过它,解决了很多小问题 (3认同)
  • 这个答案的所有功劳都归功于http://stackoverflow.com/questions/16701319/javascript-regex-split-reject-null (2认同)

小智 18

var newArray = oldArray.filter(function(v){return v!==''});
Run Code Online (Sandbox Code Playgroud)


Eri*_*est 8

请注意: 文档说:

filter是ECMA-262标准的JavaScript扩展; 因此, 它可能不存在于标准的其他实现中.您可以通过在脚本开头插入以下代码来解决此问题,允许在ECMA-262实现中使用过滤器,而这些过滤器本身不支持它.假设fn.call计算为Function.prototype.call的原始值,并且Array.prototype.push具有其原始值,则该算法正好是ECMA-262第5版中指定的算法.

因此,为了避免一些心痛,您可能必须在开始时将此代码添加到脚本中.

if (!Array.prototype.filter) {
  Array.prototype.filter = function (fn, context) {
    var i,
        value,
        result = [],
        length;
        if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
          throw new TypeError();
        }
        length = this.length;
        for (i = 0; i < length; i++) {
          if (this.hasOwnProperty(i)) {
            value = this[i];
            if (fn.call(context, value, i, this)) {
              result.push(value);
            }
          }
        }
    return result;
  };
}
Run Code Online (Sandbox Code Playgroud)

  • 基本上,不适用于IE8 (3认同)