Javascript indexOf method with multiple values

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

I have an array wich contains multiple same values

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


        
5条回答
  •  一生所求
    2021-01-02 17:55

    This kind of function doesn't exist built in, but it would be pretty easy to make it yourself. Thankfully, indexOf can also accept a starting index as the second parameter.

    function indexOfAll(array, searchItem) {
      var i = array.indexOf(searchItem),
          indexes = [];
      while (i !== -1) {
        indexes.push(i);
        i = array.indexOf(searchItem, ++i);
      }
      return indexes;
    }
    
    var array = ["test234", "test9495", "test234", "test93992", "test234"];
    document.write(JSON.stringify(indexOfAll(array, "test234")));

提交回复
热议问题