Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - 如何将对象添加到数组(How to add an object to an array)

How can I add an object to an array (in javascript or jquery)?

(如何将对象添加到数组 (使用javascript或jquery)?)

For example, what is the problem with this code?

(例如,此代码有什么问题?)

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?

    (如何将对象放入数组并将其保存到变量?)

  ask by naser translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...