JavaScript 推入已使用地图填充的数组创建了嵌套的二维数组而不是一维数组

JavaScript push on a array which has been populated using map created a nested 2d array not a 1d array

// Data
const account1 = {
  owner: 'Jason Mike',
  movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
  interestRate: 1.2, // %
  pin: 1111,
};

const account2 = {
  owner: 'Jessica Davis',
  movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
  interestRate: 1.5,
  pin: 2222,
};

const account3 = {
  owner: 'Steven Thomas Williams',
  movements: [200, -200, 340, -300, -20, 50, 400, -460],
  interestRate: 0.7,
  pin: 3333,
};

const account4 = {
  owner: 'Sarah Smith',
  movements: [430, 1000, 700, 50, 90],
  interestRate: 1,
  pin: 4444,
};

const accounts = [account1, account2, account3, account4];

//creating a owners array


const owners = [];
owners.push(accounts.map(acc => acc.owner).flat());
owners.push('Chris John');
owners.flat();

console.log(owners.sort());

输出

为什么它创建嵌套数组而不附加到现有数组

ps=> 对不起,这是我的第一个问题。如有错误请见谅

为什么要先创建一个空数组然后压入元素然后放平。

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

直接使用map会return生成一个全新的数组,然后将元素压入其中。

// Data
const account1 = {
  owner: "Jason Mike",
  movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
  interestRate: 1.2, // %
  pin: 1111,
};

const account2 = {
  owner: "Jessica Davis",
  movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
  interestRate: 1.5,
  pin: 2222,
};

const account3 = {
  owner: "Steven Thomas Williams",
  movements: [200, -200, 340, -300, -20, 50, 400, -460],
  interestRate: 0.7,
  pin: 3333,
};

const account4 = {
  owner: "Sarah Smith",
  movements: [430, 1000, 700, 50, 90],
  interestRate: 1,
  pin: 4444,
};

const accounts = [account1, account2, account3, account4];

//creating a owners array
const owners = accounts.map((acc) => acc.owner);
owners.push("Chris John");
console.log(owners);