3 回答

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

TA貢獻1853條經驗 獲得超9個贊
postcode
始終作為數組事件出現,您沒有將任何參數傳遞給函數。即使您返回值,您也會迭代
postcode
數組forEach
,但 的結尾forEach
將返回,而不是undefined
按您的預期返回。boolean
array
我使用了每種方法來測試所有元素是否通過
postcode
測試。這里它應該適用true
于所有元素,false
如果有的話它會是false
為了避免每次返回
true
都是空數組,我們應該檢查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貢獻1824條經驗 獲得超8個贊
forEach 方法并不意味著返回任何值:lambda 的返回值被丟棄。這就是為什么你得到未定義的原因。也是if... else...沒用的。forEach 對于只有一個元素的數組效果很好。您需要一個接受 lmbda 并返回值的函數。根據您的需要every,它可能是(如果所有郵政編碼匹配,則返回 true)或者可能map(返回一個布爾數組,每個傳遞的郵政編碼一個)或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));
};
添加回答
舉報