JavaScript move an item of an array to the front

前端 未结 17 920
终归单人心
终归单人心 2020-12-12 20:15

I want to check if an array contains \"role\". If it does, I want to move the \"role\" to the front of the array.

var data= [\"ema         


        
17条回答
  •  天命终不由人
    2020-12-12 20:43

    To check whether an item exists in an array you should to use .includes() instead of in (as already noted here, in is for properties in objects).

    This function does what you are looking for: (removes the item from the position it is in and reads in front)

       data = ["email","role","type","name"];
       moveToFirst("role", data)
        
       function moveToFirst(s, r){
          if (r.includes(s)){
            r.splice(r.indexOf(s),1);
            r.unshift(s);
          } 
        }
        
        console.log(data)

提交回复
热议问题