极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 解构赋值一个数组,a 取第一项默认值为 3,c 取剩下的值组成数组

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 540 (opens new window)

const list = [1, 2, 3, 4, 5];
const [a, ...c] = list;
function getTargetAndRest(target, originList) {
  let targetArr = [];
  for (let i = 0; i < originList.length; i++) {
    if (originList[i] === target) {
      targetArr = originList.splice(i, 1);
      break;
    }
  }
  return targetArr.concat(originList);
}

const list = [1, 2, 3, 4, 5];
let [a, ...c] = getTargetAndRest(3, list);

Author

回答者: wuzqZZZ (opens new window)

一楼兄弟的答案少了个默认值,小改一下

const list = [1, 2, 3, 4, 5];
const [a = 3, ...c] = list; // a: 1 c: [2,3,4,5]

const list2 = [];
const [a = 3, ...c] = list2; // a: 3 c: []
Last Updated: 9/27/2022, 2:39:59 PM