从数组中删除空string,同时保持logging没有循环?

这个问题在这里被问到: 从数组中删除空string,同时保持非空string的索引logging

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

"I", "am", "", "still", "here", "", "man" 

“从这个我希望产生以下两个数组:”

 "I", "am", "still", "here", "man" 

所有这个问题的答案都提到了循环的一种forms。

我的问题:是否有可能删除所有indexempty string 没有任何循环? 除了迭代数组之外还有其他的select吗?

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

所有的答案或build议,高度赞赏。

 var arr = ["I", "am", "", "still", "here", "", "man"] // arr = ["I", "am", "", "still", "here", "", "man"] arr = arr.filter(Boolean) // arr = ["I", "am", "still", "here", "man"] 

filter文件


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

Arrowfunction文档

 var newArray = oldArray.filter(function(v){return v!==''}); 

请注意:文档说:

filter是ECMA-262标准的JavaScript扩展; 因此在标准的其他实现中可能不存在 。 您可以通过在脚本的开头插入以下代码来解决此问题,从而允许在ECMA-262实现中使用filter,这些实现本身不支持它。 这个algorithm正好是第五版ECMA-262中规定的algorithm,假设fn.call的值是Function.prototype.call的原始值,而且Array.prototype.push有它的原始值。

所以,为了避免一些心痛,你可能不得不把这个代码添加到你的脚本开始

 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; }; } 

如果使用jQuery, grep可能是有用的:


 var arr = [ a, b, c, , e, f, , g, h ]; arr = jQuery.grep(arr, function(n){ return (n); }); 

arr现在是[ a, b, c, d, e, f, g];

即我们需要用逗号,空格或换行符分隔多个电子邮件地址,如下所示。

  var emails = EmailText.replace(","," ").replace("\n"," ").replace(" ","").split(" "); for(var i in emails) emails[i] = emails[i].replace(/(\r\n|\n|\r)/gm,""); emails.filter(Boolean); console.log(emails);