我如何添加一个对象到数组(在javascript或jquery)? 例如,这段代码有什么问题?

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

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

如何在数组中保存对象? 我如何把一个对象放在一个数组中,并将其保存到一个变量?


当前回答

JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since 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 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. 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).

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

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

用法:

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

其他回答

如果这样使用代码,就会遇到作用域问题。如果您计划在函数之间使用它,则必须在函数之外声明它(或者如果调用它,则将其作为参数传递)。

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
a=[];
a.push(['b','c','d','e','f']);

object显然是一个打字错误。但是object和array都需要大写字母。

new Array和new Object可以用简写来表示它们是[]和{}

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

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

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

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

这里数组years的值是

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

就像这样。

使用array .push()将任何东西放入数组。

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

关于数组的额外信息

一次添加多个项目

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

将项添加到数组的开头

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

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

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)

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

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