{nativescript} indexOf array

{nativescript} indexOf array

本文关键字:array indexOf nativescript      更新时间:2023-09-26

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

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

使用findinindex方法-

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

使用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'))