我如何添加一个对象到数组(在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来使用数组中的对象。
如何在数组中保存对象? 我如何把一个对象放在一个数组中,并将其保存到一个变量?
首先,没有对象或数组。有对象和数组。其次,你可以这样做:
a = new Array();
b = new Object();
a[0] = b;
现在a将是一个数组,b是它唯一的元素。
使用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']
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 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
扩展加比·普卡鲁的答案,包括对第2个问题的回答。
a = new Array();
b = new Object();
a[0] = b;
var c = a[0]; // c is now the object we inserted into a...
var years = [];
for (i= 2015;i<=2030;i=i+1){
years.push({operator : i})
}
这里数组years的值是
years[0]={operator:2015}
years[1]={operator:2016}
就像这样。
我用auto list创建对象的方法:
var list = [];
function saveToArray(x) {
list.push(x);
};
function newObject () {
saveToArray(this);
};
另一个答案是这样的。
如果你有一个这样的数组: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;
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 literal */ var aData = []; /* object constructur */ function Person(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; this.fullname = function() { // return (this.firstname + " " + this.lastname); return (`${this.firstname} ${this.lastname}`); // es6 template string }; } /* store object into array */ aData[aData.length] = new Person("Java", "Script"); // aData[0] aData.push(new Person("John", "Doe")); aData.push(new Person("Anna", "Smith")); aData.push(new Person("Black", "Pearl")); aData[aData.length] = new Person("stack", "overflow"); // aData[4] /* loop array */ for (var i in aData) { alert(aData[i].fullname()); } /* convert array of object into string json */ var jsonString = JSON.stringify(aData); document.write(jsonString);
将对象推入数组
使用ES6符号,你可以这样做:
对于追加,你可以像这样使用展开操作符:
VAR ARR1 = [1,2,3] 是 obj = 4 var newData = [...ARR1, OBJ] // [1,2,3,4] console.log(newData);
使用push,你甚至可以向数组中添加多个对象
let myArray = [];
myArray.push(
{name:"James", dataType:TYPES.VarChar, Value: body.Name},
{name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
{name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
);
性能
今天2020.12.04,我在Chrome v86、Safari v13.1.2和Firefox v83上对所选解决方案的MacOs HighSierra 10.13.6上执行测试。
结果
适用于所有浏览器
基于长度的就地解决方案(B)对于小数组是最快的,在Firefox中也适用于大数组,对于Chrome和Safari也很快 基于push (A)的in-place解决方案对于Chrome和Safari上的大数组速度最快,对于Firefox和小数组速度最快 就地解决方案C对于大数组慢,对于小数组中快 非原位解D和E对于大数组是很慢的 非就地解决方案E、F和D(在Firefox上)对于小型数组来说速度较慢
细节
我执行2个测试用例:
对于10个元素的小数组-你可以在这里运行它 对于有1M个元素的大数组-你可以在这里运行它
下面的代码片段展示了解决方案之间的差异 一个, B, C, D, E, F
PS:答案B被删除了——但实际上它是第一个使用这种技术的答案,所以如果你有机会看到它,请点击“取消删除”。
// https://stackoverflow.com/a/6254088/860099 function A(a,o) { a.push(o); return a; } // https://stackoverflow.com/a/47506893/860099 function B(a,o) { a[a.length] = o; return a; } // https://stackoverflow.com/a/6254088/860099 function C(a,o) { return a.concat(o); } // https://stackoverflow.com/a/50933891/860099 function D(a,o) { return [...a,o]; } // https://stackoverflow.com/a/42428064/860099 function E(a,o) { const frozenObj = Object.freeze(o); return Object.freeze(a.concat(frozenObj)); } // https://stackoverflow.com/a/6254088/860099 function F(a,o) { a.unshift(o); return a; } // ------- // TEST // ------- [A,B,C,D,E,F].map(f=> { console.log(`${f.name} ${JSON.stringify(f([1,2],{}))}`) }) <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script> This shippet only presents functions used in performance tests - it not perform tests itself!
这里是chrome的示例结果
你可以像这样使用扩展运算符(…):
让arr = [{num: 1、字符:“一个”},{char num: 2: " b "}); Arr =…Arr,{num: 3, char: "c"}]; / /……Arr—>扩展运算符 console.log (arr);