是否可以在添加对象的同时推送到数组?

1 javascript arrays jquery object

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

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'
  ];
)};
Run Code Online (Sandbox Code Playgroud)

Jam*_*gan 5

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

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

更多信息可以在这里找到

  • `name: 'Text' }` 需要是 `[this.name]: 'Text' }` (2认同)