STE*_*EEL 10 javascript arrays
在给定的测试中,我看到它们都返回true或false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
将它们放在一起应该是什么样的正确案例?
测试代码:
function checkUsersValid(goodUsers) {
return function allUsersValid(submittedUsers) {
//Im testing arrays here
return submittedUsers.every(function isBigEnough(element, index, array) {
return goodUsers.some(function (el, i, arr) {
return element.id == el.id;
});
});
};
}
var goodUsers = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
];
var testAllValid = checkUsersValid(goodUsers);
testAllValid([
{ id: 2 },
{ id: 1 }
]);
Run Code Online (Sandbox Code Playgroud)
Roy*_*mir 32
(如果你知道C#LINQ,它就像Any
vs All
)
some
如果有任何谓词,则返回truetrue
every
如果所有谓词都是,则返回truetrue
谓词表示bool
为每个元素返回(true/false)的函数
Pav*_*nar 13
some
is analogue to logical or
every
is analogue to logical and
logically every
implies some
, but not in reverse
try this:
var identity = function(x){return x}
console.log([true, true].some(identity))//true
console.log([true, true].every(identity))//true
console.log([true, false].some(identity))//true
console.log([true, false].every(identity))//false
console.log([false, false].some(identity))//false
console.log([false, false].every(identity))//false
console.log([undefined, true].some(identity))//true
console.log([undefined, true].every(identity))//false
console.log([undefined, false].some(identity))//false
console.log([undefined, false].every(identity))//false
console.log([undefined, undefined].some(identity))//false
console.log([undefined, undefined].every(identity))//false
Run Code Online (Sandbox Code Playgroud)
该文档回答了您的问题...
在一些()方法测试所述阵列中的一些元件是否通过由提供的功能来实现的测试。
的每一个()方法测试是否阵列中的所有元件由通过所提供的功能来实现的测试。
因此,您将根据要测试some
元素或every
元素来使用它们。
如果every() returns true
那么some() returns true
。
但
如果some() returns true
那么we cannot conclude anything about the result of every()
。