刚浏览Laravel Mix的源代码(Webpack设置)时,我遇到了一些有关设置自己的Webpack的启发。

rules.push(...[].concat(newRules))

我不知道这是什么意思,但我相信泰勒不会仅仅为了它而包括任何多余的东西。

当然这些都一样好吗?
rules.concat(newRules)

或者
rules.push(...newRules)

甚至是旧的for循环!但是,为什么在散布元素之前先连接到空数组?

如果有人能启发我,我将不胜感激。

最佳答案

我只能推测是因为我没有编写代码,但我想这样做的目的是将newRules添加到rules中,其中newRules可以是任何类型(而不仅仅是数组)。当我们希望原始数组发生变异时, concat 将创建一个新数组。 push 使数组变异,但是如何处理newRules是数组的情况?您不能只将newRules推送到rules中,因为它会是数组中的一个数组,并且您不能散布newRules,因为并非所有事情都是可迭代的。 [].concat(newRules)将所有newRules添加到一个数组,该数组本质上将非数组“转换”为数组,并在push中散布该数组将把这些项添加到rules中。

查看下面的测试用例,然后单击“运行代码段”以查看其运行情况:

const PASSED = '✅ PASSED';
const FAILED = '❌ FAILED';

(() => {
  console.log('`rules.concat(newRules)`');
  (() => {
    const expectation = [1, 2, 3, 4, 5, 6];
    const rules = [1, 2, 3];
    const newRules = [4, 5, 6];
    rules.concat(newRules);
    console.log('where `newRules` is an array:', _.isEqual(expectation, rules) ? PASSED : FAILED);
  })();

  (() => {
    const expectation = [1, 2, 3, 4];
    const rules = [1, 2, 3];
    const newRules = 4;
    rules.concat(newRules);
    console.log('where `newRules` is not an array:', _.isEqual(expectation, rules) ? PASSED : FAILED);
  })();
  console.log('');
})();

(() => {
  console.log('');
  console.log('`rules.push(newRules)`');
  (() => {
    const expectation = [1, 2, 3, 4, 5, 6];
    const rules = [1, 2, 3];
    const newRules = [4, 5, 6];
    rules.push(newRules);
    console.log('where `newRules` is an array:', _.isEqual(expectation, rules) ? PASSED : FAILED);
  })();

  (() => {
    const expectation = [1, 2, 3, 4];
    const rules = [1, 2, 3];
    const newRules = 4;
    rules.push(newRules);
    console.log('where `newRules` is not an array:', _.isEqual(expectation, rules) ? PASSED : FAILED);
  })();
  console.log('');
})();

(() => {
  console.log('');
  console.log('`rules.push(...[].concat(newRules))`');
  (() => {
    const expectation = [1, 2, 3, 4, 5, 6];
    const rules = [1, 2, 3];
    const newRules = [4, 5, 6];
    rules.push(...[].concat(newRules));
    console.log('where `newRules` is an array:', _.isEqual(expectation, rules) ? PASSED : FAILED);
  })();

  (() => {
    const expectation = [1, 2, 3, 4];
    const rules = [1, 2, 3];
    const newRules = 4;
    rules.push(...[].concat(newRules));
    console.log('where `newRules` is not an array:', _.isEqual(expectation, rules) ? PASSED : FAILED);
  })();
})();
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

10-04 16:28