{nativescript} indexOf数组

时间:2016-09-12 03:50:54

标签: javascript nativescript

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

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

2 个答案:

答案 0 :(得分:3)

使用findIndex方法 -

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

答案 1 :(得分: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'))

相关问题