indexOf与findIndex的用法
例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script type="text/javascript"> var arr1 = [1, 2, 3, 4, 5] var arr2 = [1, 2, 4, 5] for (var i = 0; i < arr1.length; i++) { if (arr2.indexOf(arr1[i]) === -1) { alert(arr1[i]) //3 } } </script> </body> </html>
获取数组中某个元素的下标,如:数组中6的下标是多少
<script> var arr = [9,8,7,6,5,4,3,2,1] console.log(arr.indexOf(6)); //3 </script>
获取数组里对象的下标,findIndex是ES6,ie浏览器不支持
<script> //获取数组对象里id为6的下标 var arr = [{id:1},{id:2},{id:6},{id:8}] var index = arr.findIndex(item => item.id ===6); console.log(index); //2 </script>