javascript - 无法使用方法(传递)索引作为参数从数组中检索数据

标签 javascript typescript

在传递索引作为参数时无法使用 method() 获取数组项 它显示为未定义

export class DataService {
    public list = [
        { id: 11, name: 'Mr. Nice' },
        { id: 12, name: 'Narco' },
        { id: 13, name: 'Bombasto' },
        { id: 14, name: 'Celeritas' },
        { id: 15, name: 'Magneta' },
        { id: 16, name: 'RubberMan' },
        { id: 17, name: 'Dynama' },
        { id: 18, name: 'Dr IQ' },
        { id: 19, name: 'Magma' },
        { id: 20, name: 'Tornado' }
    ]
    getList() {
        return this.list;
    }


    update(num, updated) {
        let list = this.getList()
        console.log(typeof (num))
        console.log(this.list[num])
    }

最佳答案

您的数组包含对象,但您希望通过 id 进行搜索,这是这些对象的属性。您必须使用过滤器:

console.log(this.list.find(el => el.id === id))

关于javascript - 无法使用方法(传递)索引作为参数从数组中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55372740/

相关文章:

JavaScript 对象数组未正确导入

javascript - Input.value 在我的 console.log 中产生了奇怪的延迟

javascript - 在这种情况下使用 Javascript 的原型(prototype)继承有什么优势吗?

javascript - Angular $resource 中的自定义实例方法

node.js - 将 ChaiHttp 与 beforeEach 或 before 方法一起使用

javascript - 如何在我的 React 类中的接口(interface)中包含接口(interface)?

javascript - 计算元素点击次数并定义最大值

javascript - 如何在动态加载的 Typescript 中扩展类

javascript - Angular 5 将日期绑定(bind)到字段( react 形式)

angular - spring boot http POST @RequestParam 多个参数