高级前端js【Q527】解构赋值一个数组,a 取第一项默认值为 3,c取剩下的值组成数组

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

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 540

Author 回答者: shfshanyue

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

Author 回答者: JoeWrights

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

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

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: []