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

这里有一个问题: 从数组中删除空字符串,同时记录非空字符串的索引

如果你注意到@Baz 所给出的东西;

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

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

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

对于这个问题,所有的 答案都提到了一种循环的形式。

我的问题是: 有没有可能使用 empty string 没有任何循环?对所有 index进行 拿开... 除了迭代数组之外还有其他选择吗?

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

非常感谢您的回答和建议。

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

filter documentation


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

Arrow functions documentation

PLEASE NOTE: The documentation says:

filter is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of filter in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that fn.call evaluates to the original value of Function.prototype.call, and that Array.prototype.push has its original value.

So, to avoid some heartache, you may have to add this code to your script At the beginning.

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;
};
}
var newArray = oldArray.filter(function(v){return v!==''});

If are using jQuery, grep may be useful:


var arr = [ a, b, c, , e, f, , g, h ];


arr = jQuery.grep(arr, function(n){ return (n); });

arr is now [ a, b, c, d, e, f, g];

i.e we need to take multiple email addresses separated by comma, spaces or newline as below.

    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);
arr = arr.filter(v => v);

as returned v is implicity converted to truthy

You can use lodash's method, it works for string, number and boolean type

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

https://lodash.com/docs/4.17.15#compact