sal*_*nxk 3 javascript arrays string nan
我尝试使用isNaN(value)and!isNaN(value)但无法在不删除字符串的情况下删除给定代码中的 NaN 元素。(显然是因为字符串不是数字)。
function cleaner(arr) {
return = arr.filter(function f(value) {return (value !== false && value !== null && value !== 0 && value !== undefined)});
}
cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]);
Run Code Online (Sandbox Code Playgroud)
上面的代码应该返回[7, "eight", 9, ""];
这将仅返回数字(不带 0)和字符串(包括空字符串)。
function cleaner(arr) {
return arr.filter(function(item){
return typeof item == "string" || (typeof item == "number" && item);
/** Any string**/ /** Numbers without NaN & 0 **/
});
}
console.log(cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]));
//[7, "eight", 9, ""]Run Code Online (Sandbox Code Playgroud)
使用 ES2015箭头函数语法
array.filter(item => typeof item == "string" || (typeof item == "number" && item));
Run Code Online (Sandbox Code Playgroud)
array.filter(item => typeof item == "string" || (typeof item == "number" && item));
Run Code Online (Sandbox Code Playgroud)