some

Defined in MDN, the some() method tests whether at least one element in the array passes the provided function test. It returns a Boolean value.

In short: it checks every item in the array, and true if one item passes.

  • It just returnstrueorfalse
  • It’s going to apply to theEach itemGet tested. NeversomeThe inside ofif elseoperation
  • Don’t inreturnWrite backtrueorfalse.returnIt’s followed by your offer

Recently do background management system encountered a requirement: pop up a Dialog, as long as the Dialog insideinputIf one of them has a value, it’s ok; Otherwise promptThere must be at least one value.The data structure is as followssome

let arr = [ { value: "apple" }, { value: "" }, { value: "banana" }, { value: "orange" }, { value: "" }, ] let res = arr.some(item=>{ return item.value ! == "" }) console.log(res);Copy the code

In this case, res is true whenever there is a value, so we can proceed to the next step when res is true.

If (res) {console.log(" Array has value "); } else {console.log(" Enter at least one value "); }Copy the code

every

Every is used in the same way as some. In MDN: the every() method tests whether all elements in an array pass the test of a given function. It returns a Boolean value.

In short: it checks every item in the array, false if any item fails. Same notes as some. If you want to have a value in every input field,

let arr2 = [ { value: "apple" }, { value: "" }, { value: "banana" }, { value: "orange" }, { value: "er" }, ] var res2 = arr2.every(item => { return item.value ! == "" }) console.log(res2);Copy the code

In this case, res2 is false as long as one of the entries has no value.

if (! Res2) {// if res2 is true, else; If false, go to if console.log(" input box empty value "); } else {console.log(" input box has no value "); Console. log(" Next step "); }Copy the code

find

In MDN, the find() method returns the value of the first element in the array that satisfies the provided test function. Find () returns a value, and is the first value that satisfies the condition

let arr3 = [ { value: "" }, { value: "" }, { value: "" }, { value: "" }, { value: "apple" }, ] var res3 = arr3.find(item => { return item.value ! == "" }) console.log(res3);Copy the code

The value of find can be determined by whether the return value of find is undefined.

If (res3) {//res3 has a value, go to the next step here. Console. log(" at least one value in array "); } else {//res3 is undefined console.log(" Array is empty!" ); }Copy the code