根据数组对象某一元素的id,找到此元素在数组所在的位置

<script>
        var data = [
            { id: 1, name: 'test' },
            { id: 2, name: 'test2' },
            { id: 3, name: 'test3' },
            { id: 4, name: 'test4' },
            { id: 5, name: 'test5' },
        ]
        var id = 2;
        // 根据数组对象某一元素的id,找到此元素在数组所在的位置(findIndex)
        var index = data.findIndex(item => item.id == id);
        console.log(index)  //1

 定义和用法

  findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。

  findIndex() 方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
  • 如果没有符合条件的元素返回 -1

  注意: findIndex() 对于空数组,函数是不会执行的。

  注意: findIndex() 并没有改变数组的原始值  语法

array.findIndex(function(currentValue, index, arr), thisValue)

   参数

参数描述
function(currentValue, index,arr) 必须。数组每个元素需要执行的函数。
函数参数:
参数描述
currentValue 必需。当前元素
index 可选。当前元素的索引
arr 可选。当前元素所属的数组对象
thisValue 可选。 传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
 
==================================================================================== other
       // 数组中两个元素置换位置
        function swapArr(arr, index1, index2) {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0];
            return arr;
        }
        console.log('swapArr ', swapArr(data, 1, 2));
        //指定数组移动到第一个位置
        function toFirst(arr, index) {
            if (index != 0) {
                arr.unshift(arr.splice(index, 1)[0]);
            }
        }
        toFirst(data, index); // 调用
        console.log('data ', data); 结果如下
    </script>

 

posted @ 2021-12-02 18:03  蓝色精灵jah  阅读(524)  评论(0编辑  收藏  举报