繁体   English   中英

"Javascript获取包含值的键索引"

[英]Javascript get Index of Key which contains value

我想知道是否有更好的方法来获取其值包含给定值的键索引,否则它返回 Null。 在下面的示例中,它可以满足我的需要,但不确定是否有更简单的编写方式。 我知道 javascript 的语法非常强大,但我并不像其他人那样熟悉它。

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}
const needle = 5;
Object.values(sets).findIndex(a => a.find(b => b === needle))

返回位置编号或 -1

const keyIndex = (obj, value) => {
  const index = Object.keys(obj).findIndex(key => obj[key].includes(value));
  return index > -1 ? index : null;
}
console.log(keyIndex(sets, 8));

我可以看到你来自哪里。 即使最终使用它们,考虑如何消除 for 循环通常也很有用。

你觉得这个版本怎么样?:

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

const newGetValueSetIndex = val => {
  const result = Object.values(sets)
    .findIndex(
      values => values.includes(val)
    )
  return result === -1 
    ? null 
    : result
}

console.log(newGetValueSetIndex(4))
console.log(newGetValueSetIndex(20))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM