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)
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]
Run Code Online (Sandbox Code Playgroud)
小智 18
var newArray = oldArray.filter(function(v){return v!==''});
Run Code Online (Sandbox Code Playgroud)
请注意: 文档说:
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)
| 归档时间: |
|
| 查看次数: |
90108 次 |
| 最近记录: |