Home>

As the title says.
For example, how can you write clearly in the following cases?

var array = ["a", "b", "c", "d", "e", "f"];
$.each (array, function (index, value) {
    if (// I want to be true only when index is 0, 1, 4
) {
         //processing
}
})
  • Answer # 1

    Hello

    truewhen

    indexis0or1or4Otherwise, an expression that would befalsewould be

    using includes
    [0, 1, 4] .includes (index)


    You can write. The following is an execution example on node.

      

    $node
      Welcome to Node.js v12.7.0.
      Type ".help" for more information.
      >[0, 1, 4] .includes (1)
      true
      >[0, 1, 4] .includes (2)
      false

  • Answer # 2

    It is not refreshing from includes, but you can also write something like the following using some.

    if ([0, 1, 4] .some (v =>v === index)) {


    If the number of elements in the array is 32 or less (the maximum value of index is 31 at most), the following pre-calculation will be performed ...

    [0, 1, 4] .reduce ((acc, v) =>acc + (1<19


    It can be written as follows.

    if (19&1<


    Although it is written, I think that it is better to stop because the intention does not appear in the code at all.
    It was a refreshing quest.

  • Answer # 3

      

    Here I want to be true only when index is 0, 1, 4

    Ifconditional expression,

    If there are multiple candidate values, you can use indexOf () by including those values ​​in the array.
    If it is included in the candidate, the index of the candidate list is returned/if it is not included,

    If the candidate value array isconst allowIndex = [0, 1, 4];

    allowIndex.indexOf (index)! ==-1

    !! ~ allowIndex.indexOf (index)

    It can be used like

    .

    const allowIndex = [0, 1, 4];
    $.each (array, function (index, value) {
        if (!! ~ allowIndex.indexOf (index)) {
             //processing
             console.log (index, value);
    }
    })

    From the appearance,jQuery.each ()is an API that has influenced the implementation of functions that scan array elements of Array objects. Be sure to check out theArray methodsfrom other respondents.
    Also, the method that makes full use of the shift operation (the second and subsequent examples of shinji709) is the method that places the highest priority on processing speed.