javascript中索引_如何获取JavaScript数组中项目的索引

javascript中索引

Suppose you have the value of an item which is contained in an array, and you want to get its index.

假设您具有数组中包含的项目的值,并且想要获取其索引。

How can you get it?

你怎么能得到它?

If the item is a primitive value, like a string or number, you can use the indexOf method of an array:

如果该项是原始值,例如字符串或数字,则可以使用数组的indexOf方法:

const letters = ['a', 'b', 'c']

const index = letters.indexOf('b')

//index is `1`

Remember that the index starts from the number 0

请记住,索引从数字0开始

If the item is an object, you can’t use this way, because if you try doing:

如果项目是对象,则不能使用这种方式,因为如果尝试这样做:

const letters = [
  {
    letter: 'a',
  },
  {
    letter: 'b',
  },
  {
    letter: 'c',
  },
]

const index = letters.indexOf({
  letter: 'b',
})

index will be -1 which means the item was not found. Because objects are compared by reference, not by their values (differently for primitive types). The object passed to indexOf is a completely different object than the second item in the array.

index-1 ,表示找不到该项目。 因为对象是通过引用而不是通过它们的值进行比较的(与原始类型不同)。 传递给indexOf的对象是与数组中第二个项目完全不同的对象。

You can use the findIndex value like this, which runs a function for each item in the array, which is passed the element, and its index. Returning from it will assign the return value to the return value of findIndex:

您可以像这样使用findIndex值,该值为数组中的每个项目运行一个函数,该函数传递给元素及其索引。 从它返回将把返回值分配给findIndex的返回值:

const letters = [
  {
    letter: 'a',
  },
  {
    letter: 'b',
  },
  {
    letter: 'c',
  },
]

const index = letters.findIndex((element, index) => {
  if (element.letter === 'b') {
    return true
  }
})

//index is `1`

翻译自: https://flaviocopes.com/how-to-get-index-item-array-javascript/

javascript中索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值