我有一個線的遺留代碼對分號分割字符串:這個字符串拆分操作中的「過濾器」調用是什麼?
var adds = emailString.split(/;+/).filter(Boolean);
什麼可以在filter(Boolean)
部分呢?
我有一個線的遺留代碼對分號分割字符串:這個字符串拆分操作中的「過濾器」調用是什麼?
var adds = emailString.split(/;+/).filter(Boolean);
什麼可以在filter(Boolean)
部分呢?
filter(Boolean)
將只保留數組中的truthy值。
filter
需要一個回調函數,通過提供Boolean
作爲參考,它會被稱爲Boolean(e)
爲陣列中的每個元件e
和將返回到filter
的操作的結果。
如果返回的值是true
,元素e
將保留在數組中,否則它不包含在數組中。
例
var arr = [0, 'A', true, false, 'tushar', '', undefined, null, 'Say My Name'];
arr = arr.filter(Boolean);
console.log(arr); // ["A", true, "tushar", "Say My Name"]
在代碼
var adds = emailString.split(/;+/).filter(Boolean);
我的猜測是字符串emailString
包含由01分隔值分號可以出現多次。
> str = '[email protected];;;;[email protected];;;;[email protected];'
> str.split(/;+/)
< ["[email protected]", "[email protected]", "[email protected]", ""]
> str.split(/;+/).filter(Boolean)
< ["[email protected]", "[email protected]", "[email protected]"]
這裏split
上這將返回["[email protected]", "[email protected]", "[email protected]", ""]
。
所以我的新的'emailString.split(「;」)。過濾器(布爾);'會做同樣的,並過濾掉造成連續的分號空字符串。謝謝。 – ProfK
你也可以添加'emailString'值 – Tushar
我不明白這個問題是如何得到兩個怯懦downvotes,但它引發的答案有兩個upvotes。 – ProfK