3 回答

TA貢獻(xiàn)2051條經(jīng)驗 獲得超10個贊
當(dāng) 時,您不會返回任何東西postcode.length > 1
。
相反,您正在遍歷postcode
數(shù)組。函數(shù)內(nèi)的 returnforEach
不執(zhí)行任何操作。
您需要決定該函數(shù)應(yīng)返回什么。它應(yīng)該只返回一個布爾值還是一個布爾值數(shù)組?
對于單個布爾值,您需要every
或some
。
布爾數(shù)組只需使用map
.

TA貢獻(xiàn)1853條經(jīng)驗 獲得超9個贊
postcode
始終作為數(shù)組事件出現(xiàn),您沒有將任何參數(shù)傳遞給函數(shù)。即使您返回值,您也會迭代
postcode
數(shù)組forEach
,但 的結(jié)尾forEach
將返回,而不是undefined
按您的預(yù)期返回。boolean
array
我使用了每種方法來測試所有元素是否通過
postcode
測試。這里它應(yīng)該適用true
于所有元素,false
如果有的話它會是false
為了避免每次返回
true
都是空數(shù)組,我們應(yīng)該檢查postcode.length > 0
.
這是代碼:
const validatePostcode = (...postcode) => {
? const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
? return postcode.length > 0 && postcode.every(item => postcodeRegex.test(item));
};

TA貢獻(xiàn)1824條經(jīng)驗 獲得超8個贊
forEach 方法并不意味著返回任何值:lambda 的返回值被丟棄。這就是為什么你得到未定義的原因。也是if... else...沒用的。forEach 對于只有一個元素的數(shù)組效果很好。您需要一個接受 lmbda 并返回值的函數(shù)。根據(jù)您的需要every,它可能是(如果所有郵政編碼匹配,則返回 true)或者可能map(返回一個布爾數(shù)組,每個傳遞的郵政編碼一個)或some(如果至少一個郵政編碼匹配,則返回 true)
const validatePostcode = (...postcode) => {
? const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
? return postcode.map(item => postcodeRegex.test(item));
};
const validateAtLeastOnePostcode = (...postcode) => {
? const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
? return postcode.some(item => postcodeRegex.test(item));
};
添加回答
舉報