我是javascript的初学者
我有一个包含
的数组array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]
我想要另一个阵列但只有长度为&gt的单词; 3
array_cleaned = ["quick","brown","jumped","lazy"]
目前的实施方式:
array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]
array_clean = [];
for(var i=0; i<array_1.length; i++){
if(array_1[i].length > 3)
array_clean.push(array_1[i]);
}
document.write(array_clean)
&#13;
但我正在寻找一种方法来实际过滤它。有什么想法吗?
答案 0 :(得分:6)
您可以使用filter
方法:
var array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"];
var array_cleaned = array_1.filter( function( element ) {
return element.length > 3;
});
console.log(array_cleaned); //["quick", "brown", "jumped", "over", "lazy"]
&#13;
答案 1 :(得分:4)
你可以过滤它
var array_cleaned = array_1.filter(function(x) {
return x.length > 3;
});
答案 2 :(得分:1)
如果您不想使用过滤功能,我认为这很好用。
arrayClean = [];
for(int i = 0; i<array1.length; i++) {
if(array1[i].length < 3) {
arrayClean[i] = array[i];
}
}