如何添加一个对象到一个数组 [英] How to add an object into an array

查看:787
本文介绍了如何添加一个对象到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何添加对象到一个数组(在JavaScript或jQuery的)?
例如,这个问题这是什么code?

 <  - 语言:郎JS  - >
功能(){
    VAR一个=新阵列();
    变种B =新的对象();
    一个[0] = B;
}

我想用这个code到许多对象保存到在功能1阵列和调用函数2使用数组对象。


  1. 如何保存对象到一个数组?

  2. 在一个阵列怎样才能得到一个对象,并将其保存到一个变量?


解决方案

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

  VAR A = [],B = {};
a.push(二);
// a [0] === B:


阵列上的额外信息

一次添加多个项目

  VAR X = ['一'];
x.push('B','C');
// X = ['一','B','C']

将项目添加到一个数组的开头

  VAR X = ['C','D'];
x.unshift('一个','B');
// X = ['一','B','C','D']

一个阵列中的内容添加到其他

  VAR X = ['一','B','C'];
变种Y = ['D','E','F'];
x.push.apply(X,Y);
// X = ['一','B','C','D','E','F']
// Y = ['D','E','F'(保持不变)

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

  VAR X = ['一','B','C'];
变种Y = ['D','E','F'];
变种Z = x.concat(Y);
// X = ['一','B','C'(保持不变)
// Y = ['D','E','F'(保持不变)
// Z = ['一','B','C','D','E','F']

How can I add an object into an array (in javascript or jquery)? For example, what is the problem this code?

<!-- language: lang-js -->
function(){
    var a = new array();
    var b = new object();
    a[0]=b;
}

I would like to use this code to save many objects into the array in function1 and call function2 to use the object in array.

  1. How can I save an object into an array?
  2. How can get an object in an array and save it to a variable?

解决方案

Put anything into an array using 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']

这篇关于如何添加一个对象到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆