【问题标题】:{nativescript} indexOf array{nativescript} indexOf 数组
【发布时间】:2016-09-12 03:50:54
【问题描述】:

我有一个如下所示的数组。当我使用this.itemsgroupcustomer.indexOf("Perorangan") 时,它返回-1。我不知道为什么这是错误的。请帮忙。

viewModel.itemsgroupcustomer = [
        {title: "Perusahaan"},
        {title: "Perorangan"}
    ];

【问题讨论】:

  • 因为数组不包含Perorangan字符串的元素。

标签: javascript nativescript


【解决方案1】:

使用 findIndex 方法 -

viewModel.itemsgroupcustomer.findIndex(x=>x.title==='Perorangan');

【讨论】:

    【解决方案2】:

    改用Array.prototype.find,它返回通过测试的元素:

    const arr = [
      {title: "Perusahaan"},
      {title: "Perorangan"}
    ]
    console.log(arr.find(el => el.title === 'Perorangan'))

    然后你可以使用返回值在数组中找到它的索引

    const arr = [
      {title: "Perusahaan"},
      {title: "Perorangan"}
    ]
    const filteredElement = arr.find(el => el.title === 'Perorangan')
    console.log(arr.indexOf(filteredElement))

    更新:

    正如用户@zerkms 所指出的,有一个内置方法可以一步完成上述操作,它是Array.prototype.findIndex

    const arr = [
      {title: "Perusahaan"},
      {title: "Perorangan"}
    ]
    console.log(arr.findIndex(el => el.title === 'Perorangan'))

    【讨论】:

    • 那里有一个Array.prototype.findIndex
    • 非常感谢@mauricio,这个数组是如何工作的?有时我迷失在阵列世界中。这是我的在线代码this.itemsgroupcustomer.indexOf( this.itemsgroupcustomer.find(el => el.title === "Perorangan"))。它返回 1。耶
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多