我如何添加一个对象到数组(在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来使用数组中的对象。
如何在数组中保存对象? 我如何把一个对象放在一个数组中,并将其保存到一个变量?
当前回答
如果这样使用代码,就会遇到作用域问题。如果您计划在函数之间使用它,则必须在函数之外声明它(或者如果调用它,则将其作为参数传递)。
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
其他回答
var years = [];
for (i= 2015;i<=2030;i=i+1){
years.push({operator : i})
}
这里数组years的值是
years[0]={operator:2015}
years[1]={operator:2016}
就像这样。
扩展加比·普卡鲁的答案,包括对第2个问题的回答。
a = new Array();
b = new Object();
a[0] = b;
var c = a[0]; // c is now the object we inserted into a...
你可以像这样使用扩展运算符(…):
让arr = [{num: 1、字符:“一个”},{char num: 2: " b "}); Arr =…Arr,{num: 3, char: "c"}]; / /……Arr—>扩展运算符 console.log (arr);
如果这样使用代码,就会遇到作用域问题。如果您计划在函数之间使用它,则必须在函数之外声明它(或者如果调用它,则将其作为参数传递)。
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
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.