Home > Article > Web Front-end > How to accurately find the position of an array element
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!