代码之家  ›  专栏  ›  技术社区  ›  Always_a_learner

OR运算符如何在javascript或typescript中的find函数中工作?

  •  -1
  • Always_a_learner  · 技术社区  · 6 年前

    myArray = [
      {id:123, name:"abc"},
      {id:234, name:"xyz"},
      {id:345, name:"pqr"}
    ]
    
    someValue = 123
    someOtherObj = {id: 234}
    
    let matchedObj = this.myArray.find(object=> object.id === somevalue || object.id === someOtherObj.id) 
    console.log(matchedObj)
    

    每次的输出是123,还是123或234?你能解释一下这是怎么回事吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   T.J. Crowder    6 年前

    find 找到 第一 匹配数组中的项。 condition1 || condition2 是真的,如果 condition1 condition2 是真的。(更具体地说: || 计算其右侧操作数并将该值作为其结果。)

    id: 234 id: 123

    const someValue = 123;
    const someOtherObj = {id: 234};
    
    function match(array) {
        console.log(array.find(object => object.id === someValue || object.id === someOtherObj.id));
    }
    
    match([
        {id:123, name:"abc"}, // Finds this one
        {id:234, name:"xyz"},
        {id:345, name:"pqr"}
    ]);
    match([
        {id:345, name:"pqr"},
        {id:234, name:"xyz"}, // Finds this one
        {id:123, name:"abc"}
    ]);