Javascript indexOf method with multiple values

后端 未结 5 2054
耶瑟儿~
耶瑟儿~ 2021-01-02 17:50

I have an array wich contains multiple same values

[\"test234\", \"test9495\", \"test234\", \"test93992\", \"test234\"]
         


        
5条回答
  •  走了就别回头了
    2021-01-02 18:06

    You can use the fromIndex of Array#indexOf.

    fromIndex

    The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. Default: 0 (entire array is searched).

    ~ is a bitwise not operator.

    It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

    value  ~value   boolean
    -1  =>   0  =>  false
     0  =>  -1  =>  true
     1  =>  -2  =>  true
     2  =>  -3  =>  true
     and so on 
    

    var array = ["test234", "test9495", "test234", "test93992", "test234"],
        result = [],
        pos = array.indexOf('test234');
    
    while (~pos) {
        result.push(pos);
        pos = array.indexOf('test234', pos + 1); // use old position incremented
    } //                               ^^^^^^^
    
    document.write('
     ' + JSON.stringify(result, 0, 4) + '
    ');

提交回复
热议问题