微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决JavaScript 推送使用地图填充的数组创建了嵌套的二维数组而不是一维数组

// 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',-200,340,-300,-20,50,400,-460],interestRate: 0.7,pin: 3333,};

const account4 = {
  owner: 'Sarah Smith',movements: [430,1000,700,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());

输出

enter image description here

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

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

解决方法

为什么要先创建一个空数组,然后推送元素,然后扁平化。

map() 方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

直接使用map,返回结果是一个全新的数组,然后将元素压入其中。

// 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",-200,340,-300,-20,50,400,-460],interestRate: 0.7,pin: 3333,};

const account4 = {
  owner: "Sarah Smith",movements: [430,1000,700,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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。