如何向数组中添加对象

时间:2021-07-08 19:41:02

How can I add an object to an array (in javascript or jquery)? For example, what is the problem with this code?

如何向数组(javascript或jquery)中添加对象?例如,这段代码有什么问题?

function(){
    var a = new array();
    var b = new object();
    a[0]=b;
}

I would like to use this code to save many objects in the array of function1 and call function2 to use the object in the array.

我想使用这段代码来保存function1数组中的许多对象,并调用function2来使用数组中的对象。

  1. How can I save an object in an array?
  2. 如何在数组中保存对象?
  3. How can I put an object in an array and save it to a variable?
  4. 如何将一个对象放入数组,并将其保存到一个变量中?

13 个解决方案

#1


494  

Put anything into an array using Array.push().

使用array .push()将任何内容放入数组。

var a=[], b={};
a.push(b);    
// a[0] === b;

Extra information on Arrays

额外的信息数组

Add more than one item at a time

一次添加多个项。

var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']

Add items to the beginning of an array

向数组的开头添加项

var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']

Add the contents of one array to another

将一个数组的内容添加到另一个数组中

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

Create a new array from the contents of two arrays

从两个数组的内容创建一个新的数组

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

#2


44  

First of all, there is no object or array. There are Object and Array. Secondly, you can do that:

首先,没有对象或数组。有对象和数组。第二,你可以这样做:

a = new Array();
b = new Object();
a[0] = b;

Now a will be an array with b as its only element.

现在a是一个数组,b是它唯一的元素。

#3


39  

var years = [];
for (i= 2015;i<=2030;i=i+1)
{
years.push({operator : i})
}

here array years is having values like

在这里,数组年份具有类似的值。

years[0]={operator:2015}
years[1]={operator:2016}

it continues like this.

继续这样下去。

#4


14  

  • JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
  • JavaScript是区分大小写的。调用new array()和new object()将抛出一个ReferenceError,因为它们不存在。
  • It's better to avoid new Array() due to its error-prone behavior.
    Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
  • 最好避免使用新的Array(),因为它容易出错。相反,将新的数组赋值为= [val1, val2, val_n]。对于对象,使用={}。
  • There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
  • 扩展数组有很多方法(如John的答案所示),但是最安全的方法是使用concat而不是push。concat返回一个新数组,保留原始数组不变。push使应该避免的调用数组发生突变,特别是当数组是全局定义的时候。
  • It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).
  • 冻结对象和新数组也是一种很好的做法,以避免意外的突变。冻结对象既不是可变的,也不是可扩展的。

Applying those points and to answer your two questions, you could define a function like this:

应用这些点并回答你的两个问题,你可以这样定义一个函数:

function appendObjTo(thatArray, newObj) {
    const frozenObj = Object.freeze(newObj);
    return Object.freeze(thatArray.concat(frozenObj));
}

Usage:

用法:

// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.

#5


8  

Expanding Gabi Purcaru's answer to include an answer to number 2.

将Gabi Purcaru的答案扩展为2的答案。

a = new Array();
b = new Object();
a[0] = b;

var c = a[0]; // c is now the object we inserted into a...

#6


6  

obejct is clearly a typo. But both object and array need capital letters.

obejct显然是一个输入错误。但是对象和数组都需要大写字母。

You can use short hands for new Array and new Object these are [] and {}

您可以使用短指针来处理新数组和新对象,这些是[]和{}

You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.

您可以使用.push将数据推入数组。这将它添加到数组的末尾。或者可以设置一个索引来包含数据。

function saveToArray() {
    var o = {};
    o.foo = 42;
    var arr = [];
    arr.push(o);
    return arr;
}

function other() {
    var arr = saveToArray();
    alert(arr[0]);
}

other();

#7


2  

a=[];
a.push(['b','c','d','e','f']);

#8


2  

The way I made object creator with auto list:

我用自动列表创建对象创建器的方法:

var list = [];

function saveToArray(x) {
    list.push(x);
};

function newObject () {
    saveToArray(this);
};

#9


2  

On alternativ answer is this.

另一种回答是。

if you have and array like this: var contacts = [bob, mary];

如果你有这样的数组:var contacts = [bob, mary];

and you want to put another array in this array, you can do that in this way:

你想在这个数组里放另一个数组,你可以这样做:

Declare the function constructor

声明的函数的构造函数

function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}

make the object from the function:

从函数中创建对象:

var add1 = new add("Alba","Fas","Des@gmail.com","[098] 654365364");

and add the object in to the array:

并将对象添加到数组中:

contacts[contacts.length] = add1;

#10


1  

Using ES6 notation, you can do something like this:

使用ES6表示法,你可以这样做:

var arr1 = [1,2,3]
var obj = 4

For appending you can use the spread operator like this:

对于附加,您可以使用如下的扩展操作符:

var newData = [...arr1, obj] // [1,2,3,4]

#11


0  

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).

如果您这样使用代码,那么您将遇到范围问题。如果您打算在函数之间使用它(或者调用它时,将它作为参数传递),则必须在函数之外声明它。

var a = new Array();
var b = new Object();

function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}

function second() {
var c = a[0];
}

// code
first();
// more code
second();
// even more code

#12


0  

/* array literal */
var aData = [];

/* object constructur */
function Data(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.fullname = function() {
    return (this.firstname + " " + this.lastname);
  };
}

/* store object into array */
aData.push(new Data("Jhon", "Doe"));
aData.push(new Data("Anna", "Smith"));
aData.push(new Data("Black", "Pearl"));

/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);

/* loop arrray */
for (var x in aData) {
  alert(aData[x].fullname());
}

#13


-3  

You can use this prototype of javascript like this:

您可以使用如下的javascript原型:

Array.prototype.push.apply(array1, array2,array3);

=> array1 contains the rest of them

=> array1包含其余的

#1


494  

Put anything into an array using Array.push().

使用array .push()将任何内容放入数组。

var a=[], b={};
a.push(b);    
// a[0] === b;

Extra information on Arrays

额外的信息数组

Add more than one item at a time

一次添加多个项。

var x = ['a'];
x.push('b', 'c');
// x = ['a', 'b', 'c']

Add items to the beginning of an array

向数组的开头添加项

var x = ['c', 'd'];
x.unshift('a', 'b');
// x = ['a', 'b', 'c', 'd']

Add the contents of one array to another

将一个数组的内容添加到另一个数组中

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
x.push.apply(x, y);
// x = ['a', 'b', 'c', 'd', 'e', 'f']
// y = ['d', 'e', 'f']  (remains unchanged)

Create a new array from the contents of two arrays

从两个数组的内容创建一个新的数组

var x = ['a', 'b', 'c'];
var y = ['d', 'e', 'f'];
var z = x.concat(y);
// x = ['a', 'b', 'c']  (remains unchanged)
// y = ['d', 'e', 'f']  (remains unchanged)
// z = ['a', 'b', 'c', 'd', 'e', 'f']

#2


44  

First of all, there is no object or array. There are Object and Array. Secondly, you can do that:

首先,没有对象或数组。有对象和数组。第二,你可以这样做:

a = new Array();
b = new Object();
a[0] = b;

Now a will be an array with b as its only element.

现在a是一个数组,b是它唯一的元素。

#3


39  

var years = [];
for (i= 2015;i<=2030;i=i+1)
{
years.push({operator : i})
}

here array years is having values like

在这里,数组年份具有类似的值。

years[0]={operator:2015}
years[1]={operator:2016}

it continues like this.

继续这样下去。

#4


14  

  • JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
  • JavaScript是区分大小写的。调用new array()和new object()将抛出一个ReferenceError,因为它们不存在。
  • It's better to avoid new Array() due to its error-prone behavior.
    Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
  • 最好避免使用新的Array(),因为它容易出错。相反,将新的数组赋值为= [val1, val2, val_n]。对于对象,使用={}。
  • There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
  • 扩展数组有很多方法(如John的答案所示),但是最安全的方法是使用concat而不是push。concat返回一个新数组,保留原始数组不变。push使应该避免的调用数组发生突变,特别是当数组是全局定义的时候。
  • It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).
  • 冻结对象和新数组也是一种很好的做法,以避免意外的突变。冻结对象既不是可变的,也不是可扩展的。

Applying those points and to answer your two questions, you could define a function like this:

应用这些点并回答你的两个问题,你可以这样定义一个函数:

function appendObjTo(thatArray, newObj) {
    const frozenObj = Object.freeze(newObj);
    return Object.freeze(thatArray.concat(frozenObj));
}

Usage:

用法:

// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.

#5


8  

Expanding Gabi Purcaru's answer to include an answer to number 2.

将Gabi Purcaru的答案扩展为2的答案。

a = new Array();
b = new Object();
a[0] = b;

var c = a[0]; // c is now the object we inserted into a...

#6


6  

obejct is clearly a typo. But both object and array need capital letters.

obejct显然是一个输入错误。但是对象和数组都需要大写字母。

You can use short hands for new Array and new Object these are [] and {}

您可以使用短指针来处理新数组和新对象,这些是[]和{}

You can push data into the array using .push. This adds it to the end of the array. or you can set an index to contain the data.

您可以使用.push将数据推入数组。这将它添加到数组的末尾。或者可以设置一个索引来包含数据。

function saveToArray() {
    var o = {};
    o.foo = 42;
    var arr = [];
    arr.push(o);
    return arr;
}

function other() {
    var arr = saveToArray();
    alert(arr[0]);
}

other();

#7


2  

a=[];
a.push(['b','c','d','e','f']);

#8


2  

The way I made object creator with auto list:

我用自动列表创建对象创建器的方法:

var list = [];

function saveToArray(x) {
    list.push(x);
};

function newObject () {
    saveToArray(this);
};

#9


2  

On alternativ answer is this.

另一种回答是。

if you have and array like this: var contacts = [bob, mary];

如果你有这样的数组:var contacts = [bob, mary];

and you want to put another array in this array, you can do that in this way:

你想在这个数组里放另一个数组,你可以这样做:

Declare the function constructor

声明的函数的构造函数

function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}

make the object from the function:

从函数中创建对象:

var add1 = new add("Alba","Fas","Des@gmail.com","[098] 654365364");

and add the object in to the array:

并将对象添加到数组中:

contacts[contacts.length] = add1;

#10


1  

Using ES6 notation, you can do something like this:

使用ES6表示法,你可以这样做:

var arr1 = [1,2,3]
var obj = 4

For appending you can use the spread operator like this:

对于附加,您可以使用如下的扩展操作符:

var newData = [...arr1, obj] // [1,2,3,4]

#11


0  

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).

如果您这样使用代码,那么您将遇到范围问题。如果您打算在函数之间使用它(或者调用它时,将它作为参数传递),则必须在函数之外声明它。

var a = new Array();
var b = new Object();

function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}

function second() {
var c = a[0];
}

// code
first();
// more code
second();
// even more code

#12


0  

/* array literal */
var aData = [];

/* object constructur */
function Data(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.fullname = function() {
    return (this.firstname + " " + this.lastname);
  };
}

/* store object into array */
aData.push(new Data("Jhon", "Doe"));
aData.push(new Data("Anna", "Smith"));
aData.push(new Data("Black", "Pearl"));

/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);

/* loop arrray */
for (var x in aData) {
  alert(aData[x].fullname());
}

#13


-3  

You can use this prototype of javascript like this:

您可以使用如下的javascript原型:

Array.prototype.push.apply(array1, array2,array3);

=> array1 contains the rest of them

=> array1包含其余的