查找某个元素在数组中的下标

第一种:利用数组的findIndex方法,适用于元素是数字或者字符串
1
2
3
4
5
6
// 查找元素b的下标
const arr = ['a', 'b', 'c']
const index = arr.findIndex(item => {
return item === 'b'
})
console.log(index) // 1
第二种:利用lodash插件中的findIndex方法,适用于元素是对象

首先,通过npm安装

1
$ npm i --save lodash

然后在项目中引入

1
import _ from 'lodash'

用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const arr = [
{
name: 'xiaoming',
age: 16
},
{
name: 'lili',
age: 18
},
{
name: 'andy',
age: 3
}
]
const index = _.findIndex(arr, { name: 'andy' })
console.log(index) // 2

扩展:lodash的深拷贝

1
2
3
4
5
const obj = {
name: 'xiaoming',
age: 16
}
const clonedObj = _.cloneDeep(obj)
--本文结束感谢您的阅读--