简体   繁体   English

无法在 JavaScript 中推送到数组

[英]Can't push to array in JavaScript

I get an error when I run this code:运行此代码时出现错误:

var array = [];

array.push(["one"]:[1,2,3]);
array.push(["two"]:[4,5,6]);

I want my array to look like this in the end: {"one": [1,2,3], "two": [4,5,6]};我希望我的数组最终看起来像这样: {"one": [1,2,3], "two": [4,5,6]};

I don't know how to fix this error, I want to use push .我不知道如何解决这个错误,我想使用push

An associative array in JavaScript is an object, so you can't use array.push as that's not valid there. JavaScript 中的关联数组是一个对象,因此您不能使用 array.push,因为它在那里无效。 You'd just want: array["one"] = [1,2,3]你只想要: array["one"] = [1,2,3]

You should be opting for something like below.你应该选择像下面这样的东西。 Using push, you will not achieve your desired output.使用推送,您将无法获得所需的输出。

let obj = {};

const item1 = {
  ["one"]: [1, 2, 3]
}
const item2 = {
  ["two"]: [4, 5, 6]
}

obj = {
  ...obj,
  ...item1,
  ...item2
}

The reason you got the error is because you are missing object wrapper notation in your push {}您收到错误的原因是因为您在 push {}中缺少对象包装符号

array.push({["one"]:[1,2,3]});
array.push({["two"]:[4,5,6]});

but as said, this will not give the desired output: {"one": [1,2,3], "two": [4,5,6]};但如前所述,这不会给出所需的输出: {"one": [1,2,3], "two": [4,5,6]};

var array = {};

array.one = [123, 123];
array.two = [123, 123];

console.log(array)

output { one: [ 123, 123 ], two: [ 123, 123 ] }输出 { 一:[ 123, 123 ],二:[ 123, 123 ] }

You must first create the object, assign values into the object, then push it into the array.您必须首先创建对象,将值分配给对象,然后将其推送到数组中。 Refer to this post for more information.有关更多信息,请参阅此帖子。 push object into array 将对象推入数组

Javascript doesn't have Associative Arrays like other languages, but it have Objects, that is similar. Javascript 不像其他语言那样有关联数组,但它有对象,这是相似的。

var object = {};

object.one = [1,2,3];

// or if the key name comes from a variable:

var key = "two";

object[key] = [4,5,6];

"one" is an object not an array. “一个”是一个对象而不是一个数组。 remove the parenthesis from there.从那里删除括号。 See below code:见下面的代码:

array.push({"one":[1,2,3]});
array.push({"two":[4,5,6]});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM