我如何添加一个对象到数组(在javascript或jquery)? 例如,这段代码有什么问题?
function() {
var a = new array();
var b = new object();
a[0] = b;
}
我想使用这段代码来保存function1数组中的许多对象,并调用function2来使用数组中的对象。
如何在数组中保存对象? 我如何把一个对象放在一个数组中,并将其保存到一个变量?
我如何添加一个对象到数组(在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.
其他回答
使用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']
另一个答案是这样的。
如果你有一个这样的数组:var contacts = [bob, mary];
你想在这个数组中放入另一个数组,你可以这样做:
声明函数构造函数
function add (firstName,lastName,email,phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}
从函数中创建对象:
var add1 = new add("Alba","Fas","Des@gmail.com","[098] 654365364");
并将对象添加到数组中:
contacts[contacts.length] = add1;
使用ES6符号,你可以这样做:
对于追加,你可以像这样使用展开操作符:
VAR ARR1 = [1,2,3] 是 obj = 4 var newData = [...ARR1, OBJ] // [1,2,3,4] console.log(newData);
a=[];
a.push(['b','c','d','e','f']);
首先,没有对象或数组。有对象和数组。其次,你可以这样做:
a = new Array();
b = new Object();
a[0] = b;
现在a将是一个数组,b是它唯一的元素。