Javascript 如何将对象添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6254050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:57:49  来源:igfitidea点击:

How to add an object to an array

javascriptarraysobject

提问by naser

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. How can I put an object in an array and save it to a variable?
  1. 如何将对象保存在数组中?
  2. 如何将对象放入数组并将其保存到变量中?

回答by John Strickler

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']

回答by santhosh

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.

它继续这样。

回答by Gabi Purcaru

First of all, there is no objector array. There are Objectand Array. Secondly, you cando that:

首先,没有objector array。有ObjectArray。其次,你可以这样做:

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

Now awill be an array with bas its only element.

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

回答by Aayushi

Using ES6notation, you can do something like this:

使用ES6符号,您可以执行以下操作:

For appending you can use the spread operatorlike this:

对于附加,您可以像这样使用扩展运算符

var arr1 = [1,2,3]
var obj = 4
var newData = [...arr1, obj] // [1,2,3,4]
console.log(newData);

回答by Boghyon Hoffmann

  • JavaScript is case-sensitive. Calling new array()and new object()will throw a ReferenceErrorsince they don't exist.
  • 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 = {}.
  • 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 concatinstead of push. concatreturns a new array, leaving the original array untouched. pushmutates the calling array which should be avoided, especially if the array is globally defined.
  • It's also a good practice to freezethe object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).
  • JavaScript区分大小写。调用new array()andnew object()会抛出 aReferenceError因为它们不存在。
  • new Array()由于其容易出错的行为,最好避免。
    相反,将新数组分配给 = [val1, val2, val_n]. 对于对象,使用= {}.
  • 扩展数组有很多方法(如 John 的回答所示),但最安全的方法是使用concat代替pushconcat返回一个新数组,原数组不变。push改变应该避免的调用数组,特别是如果数组是全局定义的。
  • 冻结对象以及新数组以避免意外突变也是一个很好的做法。冻结的对象既不可变也不可扩展(浅层)。

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.

回答by Sam

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...

回答by antelove

/* 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[aData.length] = new Data("Java", "Script"); // aData[0]

aData.push(new Data("Jhon", "Doe"));
aData.push(new Data("Anna", "Smith"));
aData.push(new Data("Black", "Pearl"));

aData[aData.length] = new Data("stack", "overflow"); // aData[4]

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

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

回答by Raynos

obejctis clearly a typo. But both objectand arrayneed capital letters.

obejct显然是一个错字。但两者objectarray需要大写字母。

You can use short hands for new Arrayand new Objectthese are []and {}

你可以使用短手new Arraynew Object这些是[]{}

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();

回答by Po Po

On alternativ answer is this.

在替代答案是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","[email protected]","[098] 654365364");

and add the object in to the array:

并将对象添加到数组中:

contacts[contacts.length] = add1;

回答by harjinder singh

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