JavaScript 循环 跳出循环问题

JavaScript 循环 跳出循环问题
例如有这么两组数据

let a = [
                        {
                            "value": "S",
                            "id": 1
                        },
                        {
                            "value": "M",
                            "id": 2
                        },
                        {
                            "value": "L",
                            "id": 3
                        },
                        {
                            "value": "XL",
                            "id": 4
                        },
                        {
                            "value": "XXL",
                            "id": 5
                        },
                        {
                            "value": "XXXL",
                            "id": 6
                        }
                    ]


let b = [1,2,3,4];

需求是这样的:如果 a 下 有 b下的值 给 对应a下添加 haseB = true

//二重循环? 跑一下看看
a.map((itema)=>{
     b.map((itemb)=>{
          itema.id === itemb?
             itema.haseB = true
        //  要跳出呀,然后继续执行,但是没 continue,加个return 看下呢?
           :
             null
       })
})
console.log(JSON.stringify(a))    
 [{"value":"S","id":1,"haseB":false},
{"value":"M","id":2,"haseB":false},
{"value":"L","id":3,"haseB":false},
{"value":"XL","id":4,"haseB":true},
{"value":"XXL","id":5,"haseB":false},
{"value":"XXXL","id":6,"haseB":false}]

//加 return false 结果  emm, 符合预期

[{"value":"S","id":1,"haseB":true},
{"value":"M","id":2,"haseB":true},
{"value":"L","id":3,"haseB":true},
{"value":"XL","id":4,"haseB":true},
{"value":"XXL","id":5},
{"value":"XXXL","id":6}]

//另外一个奇巧技淫
a.map((itema)=>{
  b.find((e)=>{
     if(itema.id===e){
       itema.haseB=true
      return e
   }
 })
})


介绍下find用法:
·
**find()** 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

·

var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
  return element > 10;
});

console.log(found);
// expected output: 12

你可能感兴趣的:(JavaScript 循环 跳出循环问题)