Home  >  Article  >  Web Front-end  >  How to accurately find the position of an array element

How to accurately find the position of an array element

巴扎黑
巴扎黑Original
2017-07-24 17:06:412839browse

Title description

Find the position of the element item in the given array arr

Output description:

If item exists in the array, return the element The position in the array, otherwise -1 is returned
Input

indexOf([ 1, 2, 3, 4 ], 3)
Output

2

1 function indexOf(arr, item) {2     for(var i=0;i<arr.length;i++){3         if(arr[i]==item)4             return i;5         6     }7     return -1;8 }//此方法利用常见for循环从头遍历

1 function indexOf(arr, item) {

2  return arr.indexOf(item);

// This method uses the indexOf() method of the JavaScript Array object. The indexOf() method can return the position where a specified string value first appears in the string. If the string is not found, it returns -1.

}

The above is the detailed content of How to accurately find the position of an array element. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn