【问题标题】:Is it possible to push to an array the same time as I add an object?是否可以在添加对象的同时推送到数组?
【发布时间】:2020-07-11 10:15:19
【问题描述】:

我想在向数组添加对象的同时将值推送到数组。这可能吗? 这是我的代码的简短演示:

let abc = [
  [],
  {}
];

$('form').find('input').each(function() {
  // This works but I'd like to do it in one step if possible
  abc[0].push(this);
  abc[1][this.name] = 'Text';

  // I'd like to change it to something like this
  abc = [
    this,
    this.name: 'Text'
  ];
)};

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    为此,您需要 ES6 扩展运算符

    abc = [
      [ ...abc[0], this ],
      { ...abc[1], [this.name]: 'Text' },
      ...abc.slice(2)
    ];
    

    更多信息可以在这里找到

    【讨论】:

    • name: 'Text' } 需要是 [this.name]: 'Text' }
    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2012-05-11
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多