【问题标题】:add an element to array in Javascript在Javascript中向数组添加元素
【发布时间】:2018-08-15 05:16:04
【问题描述】:

在我对 stackoverflow 进行了一些搜索以寻找类似问题但找不到类似问题后,我发布了这个问题。

const x =  {country: 'Sweden'};
const y =  {{name: 'james',status:'Green'},
   { name: 'Dave', status: 'Yellow'}};

预期输出:

const z = {{name: 'james',status:'Green', country: 'Sweden'},
   { name: 'Dave', status: 'Yellow', country: 'Sweden'}};

我使用 forEach 循环并尝试 .push() 或 .concat() 到循环的一个元素,但收到错误“concat 不是函数”和“pushis 不是函数”

  y.forEach(function(element) {
    x = x.concat(element); 
    console.log(x);  
  });

【问题讨论】:

  • 您的代码中没有声明一个数组。其中大部分是无效的对象声明。

标签: javascript arrays foreach concat


【解决方案1】:

根据 javascript,常量 y 是错误的。首先,请将其设为如下所示的数组。

const y =  [{name: 'james',status:'Green'},
            { name: 'Dave', status: 'Yellow'}];

const x =  {country: 'Sweden'};

那么,

y.forEach(function(element) {
   element.country  = x.country; 
   console.log(x);  
 });

【讨论】:

    【解决方案2】:

    你可以使用Object.assign()方法:

    const z = y.map(o => Object.assign(o, x));
    

    演示:

    const x =  {country: 'Sweden'};
    const y =  [
      {name: 'james',status:'Green'},
      {name: 'Dave', status: 'Yellow'}
    ];
    
    const z = y.map(o => Object.assign(o, x));
    
    console.log(z);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    您也可以使用扩展语法:

    const z = y.map(o => ({...o, ...x}));
    

    演示:

    const x =  {country: 'Sweden'};
    const y =  [
      {name: 'james',status:'Green'},
      {name: 'Dave', status: 'Yellow'}
    ];
    
    const z = y.map(o => ({...o, ...x}));
    
    console.log(z);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      相关资源
      最近更新 更多