删除仅限空格的数组元素 [英] Remove Whitespace-only Array Elements
问题描述
由于使用array.splice就地修改了数组,如何在不抛出错误的情况下从数组中删除所有仅空白元素?使用PHP,我们有preg_grep,但我在JS中如何正确地执行此操作。
由于上述原因,以下操作无效:
for(var i = 0,l = src.length; i< l; i ++){
if(src [ i] .match(/ ^ [\\\] {2,} $ /)!== null)src.splice(i,1);
}
错误:
未捕获的TypeError:无法调用未定义的方法'匹配'
从数组中删除仅空白元素的更好方法。
var array = [' 1','','c'];
array = array.filter(function(str){
return /\S/.test(str);
});
说明:
Array.prototype.filter
返回一个新数组,其中只包含函数返回的元素 true
(或真值)。 / p>
/ \S /
是一个与非空白字符匹配的正则表达式。 /\S/.test( str)
返回 str
是否有非空白字符。
Since using array.splice modifies the array in-place, how can I remove all whitespace-only elements from an array without throwing an error? With PHP we have preg_grep but I am lost as to how and do this correctly in JS.
The following will not work because of above reason:
for (var i=0, l=src.length; i<l; i++) {
if (src[i].match(/^[\s\t]{2,}$/) !== null) src.splice(i, 1);
}
Error:
Uncaught TypeError: Cannot call method 'match' of undefined
A better way to "remove whitespace-only elements from an array".
var array = ['1', ' ', 'c'];
array = array.filter(function(str) {
return /\S/.test(str);
});
Explanation:
Array.prototype.filter
returns a new array, containing only the elements for which the function returns true
(or a truthy value).
/\S/
is a regex that matches a non-whitespace character. /\S/.test(str)
returns whether str
has a non-whitespace character.
这篇关于删除仅限空格的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!