[英]check all rows within an array if value exist
我正在嘗試檢查數組屬性中是否存在值,應該彈出警報,如果沒有,則應登錄控制台。 用我當前的代碼,這就是我得到的結果
用戶數據錯誤
[{"primary_contact":"+1111111111","secondary_contact":null},{"primary_contact":"+2222222222","secondary_contact":"+2"}]
碼
for (let r = 0; r < this.global.userData.length; r++) {
if (this.global.userData[r].primary_contact === this.formattedNumber1) {
alert('Phone Number has been used already');
} else {
console.log('push data')
}
}
當我發送+1111111111
作為formattedNumber1時,會彈出警報,但是當我設置+2222222222
,警報不會彈出,並且會在控制台中寫入,但它應該能夠彈出警報cos +2222222222
也存在於陣列中
您的數組無效。 我相信這是一個錯字。 請參閱下面的示例代碼,其中已修復了數組。
另一個替代解決方案可以是使用Array.Some() :
let arr = [{
"primary_contact": "+1111111111",
"secondary_contact": null
}, {
"primary_contact": "+2222222222",
"secondary_contact": "+2"
}];
function contactExists(contact) {
return arr.some(function(el) {
return el.primary_contact === contact;
});
}
console.log(contactExists('+1111111111')); // true
console.log(contactExists('+2222222222')); // true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.