我喜歡在 javascript 中使用 .every() 和 .some() 并且遇到了它們的行為差異,我沒有在 MDN 上看到關于原因的解釋。根據 MDN,如果你在一個空陣列上運行 .every() ,結果為真,因為在數學中空集的所有元素都將匹配一個條件。但是 .some() 在空陣列上運行時將回傳 false。
const myArray = [];
const ev = myArray.every( elem => {
elem === 'this is foobared';
});
const so = myArray.some( elem => {
elem === 'this is foobared';
});
// ev is true
// so is false
我是一個很少有大腦的熊,但似乎如果空集的每個元素都匹配條件,那么一些元素匹配條件,因為如果所有元素都匹配,.some() 將為真。
const myArray = [1, 2, 3, 4];
const ev = myArray.every( elem => {
return elem < 10;
});
const so = myArray.some( elem => {
return elem < 10;
});
// ev is true
// so is true
這背后有什么邏輯嗎?
感謝您的任何解釋。
uj5u.com熱心網友回復:
這樣做的原因是它允許這些操作的關聯屬性正常作業。
此屬性需要以下等價物:
array1.every(condition) && array2.every(condition) == array1.concat(array2).every(condition);
array1.some(condition) || array2.some(condition) == array1.concat(array2).some(condition);
替換array2為空陣列,您將看到定義[].every(condition)astrue和[].some(condition)asfalse將確保在邊界情況下實作等價。
這類似于操作員true的身份值和&&操作員false的身份的方式||。
uj5u.com熱心網友回復:
一些(任何)與每個(全部):基本區別
您可以輕松記住every[And &&] 和
some[Or ||]
讓我向您展示一些物件陣列示例。
可以閱讀every() 和 some() 方法有什么區別
// Example
let users = [ {id:1, type: 'student'}, {id: 2, type: 'student'} ];
let isEveryStudent = users.every(user => user.type === 'student');
console.log('isEveryStudent', isEveryStudent);
// ```isEveryStudent``` is true because All users are student
users = [ {id:1, type: 'student'}, {id: 2, type: 'officer'} ];
isEveryStudent = users.every(user => user.type === 'student');
console.log('isEveryStudent', isEveryStudent);
// ```isEveryStudent``` is false because one of the user is officer
users = [ {id:1, type: 'student'}, {id: 2, type: 'officer'} ];
const isSomeOfficer = users.some(user => user.type === 'officer');
console.log('isSomeOfficer', isSomeOfficer);
// ```isSomeOfficer``` is true because one of the user is officer
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481229.html
標籤:javascript 数组
上一篇:在Java中向陣列添加字母
下一篇:嘗試將元素添加到動態陣列
