根据对象属性查找数组里当前对象

240 阅读1分钟

现在有个数组对象:

每一项会有 idname

const list=[
    {id: 1, name: 'this 1'},
    {id: 2, name: 'this 2'}
]

根据 id 查询当前的对象

思路:

1. 使用 Array.prototype.find() 方法

  • find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

  • 语法:arr.find(callback[, thisArg])

  • callback:在数组的每一项上执行,接收 3 个参数: - 第一个参数 element:当前遍历到的元素。 - 第二个参数 index(可选):当前遍历到的元素的 index。 - 第二个参数 array(可选):数组本身。

  • thisArg(可选):执行回调时用作 this 的对象。

  • 只要知道里面可以写一个回调,第一个参数是当前遍历的元素就行了!

2. 小试牛刀

list.find(element => element.id === 1 )
// expected output: {id: 1, name: 'this 1'}

3. 现在的查询条件 id 还不够「灵活」,可以让 id 变成一个「全局变量」—— currentId

const currentId = 1
    
list.find(element => element.id === currentId )
// expected output: {id: 1, name: 'this 1'}

注意: 这不是 闭包currentId 是「全局变量」!

如果你有更好的方法,请在评论区评论!


完。