Removing empty or undefined elements from an array
This question already has an answer here:
这是我过去写的一个有用的代码片段。
Array.prototype.empty = function() {
for (var i = 0, s = this.length; i < s; i++) { this.pop(); }
return this;
};
Array.prototype.removeAll = function(item) {
var result = [];
for (var i = 0, j = 0, s = this.length; i < s; i++) {
if (this[i] != item) { result[j++] = this[i]; }
}
this.empty();
for (var i = 0, s = result.length; i < s;) { this.push(result[i++]); }
};
您可以将数组传递给临时数组,而不添加空或未定义的数组
function clean(item) {
var tempArr = [];
for (var i = 0; i < item.length; i++) {
if (item[i] !== undefined && item[i] != "") {
tempArr.push(item[i]);
}
}
return tempArr;
}
arr = arr.filter((entry) => { return entry.trim() != '' })
链接地址: http://www.djcxy.com/p/37750.html
上一篇: JavaScript:分割字母后跟数字
下一篇: 从数组中删除空或未定义的元素