根据两个属性查找对象的键

Find key for object based on two properties

现在我可以通过搜索频率找到笔记列表的对象键:

let key = noteKeys.find(k=>note[k]['freq']===freq);

每个音符都有自己独特的频率,所以这是音符问题。

但是假设我想根据音符字母值(数字)和八度在我的音符对象中找到对象键?

我想它会是这样的,但它给了我错误“格式错误的参数列表”:

let key = noteKeys.find(k=>note[k]['note']===newNote && k=>note[k]['octave']===currentOctave)

=>是将参数与arrow functions.

的函数体分开的部分

在表达式内部会抛出错误,因为参数列表错误。

let key = noteKeys.find(k =>
        note[k]['note'] === newNote && note[k]['octave'] === currentOctave
    );

短一点

let key = noteKeys.find(k => 
        note[k].note === newNote && note[k].octave === currentOctave
    );

=> 之后的所有内容都是函数体,在这种情况下(由于缺少表示块的花括号)也是函数的 return 表达式。

通过执行 && k=> ... 您将创建一个新的匿名函数,其布尔表达式中的 truthy-ness 将始终为真。

删除第二个 k =>,您将得到一个布尔表达式,它断言 note[k]['note']===newNotenote[k]['octave']===currentOctave:

let key = noteKeys.find(k=>note[k]['note']===newNote && note[k]['octave']===currentOctave)

或者,也许更容易理解:

let key = noteKeys.find(k=> {
  return note[k]['note'] === newNote && note[k]['octave'] === currentOctave)
})

作为后续,您应该阅读箭头函数和布尔表达式。