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

<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 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 @ 2022-05-06 10:16  YoYo/切克闹  阅读(328)  评论(0编辑  收藏  举报