[英]Why won't this code work on a string?
所以我正在練習算法(javascript),我遇到了這個挑戰,我們必須過濾一個數組,刪除以下元素:
假,NaN,未定義,“”,空,0
我的代碼似乎在字符串和字符方面有問題,它沒有通過這些測試。
-bouncer([7, "ate", "", false, 9]) 應該返回 [7, "ate", 9] (返回 [7, 9])
-bouncer(["a", "b", "c"]) 應該返回 ["a", "b", "c"] (返回 [])
function bouncer(arr) {
return arr.filter(function(element)
{
if (element != false && !isNaN(element) && element != null && element != "" && element != undefined)
{return element;}
}
);
}
我想對我缺少的概念做一個簡單的解釋
function bouncer(arr) {
return arr.filter(function(element) {
if (element) {
return element;
}
}
);
}
這是給你的答案。
除了使用!=
而不是!==
給定的強制轉換問題之外,您還可以使用Boolean
作為回調進行過濾,該回調返回真實元素。
function bouncer(arr) { return arr.filter(Boolean); } console.log(bouncer([7, "ate", "", false, 9])); // [7, "ate", 9] console.log(bouncer(["a", "b", "c"])); // ["a", "b", "c"]
以下代碼適用於所有條件。 請看一看。
function bouncer(arr) {
return arr.filter(function(element) {
if (element && element.trim().length > 0 && element != "NaN") {
return element;
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.