我正在以下方法中決議來自 CSV 的一些電子郵件,并且我收到無法讀取未定義的屬性(正在讀取“電子郵件地址”)。我什至嘗試過濾掉未定義的結果,但沒有運氣。如何過濾未定義的。
const getContactsFromText = (text) => {
if(text == "" || text.trim() == '' || text === undefined){
settingTheAlert();
return;
}
const contacts = text.split(/[,;\n]/)
.filter(x => x.length > 0)
.map(x => x.trim())
.map(x => {
const [, , displayName = '', emailAddress = ''] = x.match(/"?((.*?)"?\s*<)?([^">]*)/);
if (!emailAddress && !displayName) return;
if(emailAddress === undefined) return;
return { id: emailAddress, emailAddress, displayName, isChecked: true };
})
.filter(x => isValidEmail(x.emailAddress))
.sort(sortByEmail);
if(contacts.length < 1){
settingTheAlert();
return;
}
onImport(contacts);
}
const isValidEmail = (email) => {
const EMAIL_RE = /^(([^<>()[\]\\.,;:\s@"] (\.[^<>()[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/;
const isValid = EMAIL_RE.test(String(email).toLowerCase());
if (!isValid) console.log('invalidEmail', { email })
return isValid;
}
uj5u.com熱心網友回復:
在您的代碼中:
.map(x => {
const [, , displayName = '', emailAddress = ''] = x.match(/"?((.*?)"?\s*<)?([^">]*)/);
if (!emailAddress && !displayName) return;
if (emailAddress === undefined) return; // this is useless (it's covered above)
return { id: emailAddress, emailAddress, displayName, isChecked: true };
};
})
您在這些行上隱式回傳任何內容/未定義:
if (!emailAddress && !displayName) return;
if (emailAddress === undefined) return; // again, this line is not needed
這相當于回傳undefined。然后在隨后filter你假設x.emailAddress存在,但它可能不存在,就像上面你在某些極端情況下回傳 undefined 一樣。
為了解決這個問題,您可以:
- 必須改變你的
filter功能(可能是最好的解決方案) - 使
isValidEmail函式期望整個電子郵件物件而不是期望的字串(可能不太理想)
如果您采用第一種方法,它應該類似于:
// ... other code
.map(x => {
const [, , displayName = '', emailAddress = ''] = x.match(/"?((.*?)"?\s*<)?([^">]*)/)
if (!emailAddress && !displayName) {
return null
}
return { id: emailAddress, emailAddress, displayName, isChecked: true }
})
.filter(emailObj => emailObj && isValidEmail(emailObj.emailAddress)) // checking first that the emailObj is not undefined and then checking if the emailObj.emailAddress is valid.
應該管用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451267.html
標籤:javascript 反应
