[英]how can I set my objects in array?
I have lots of details. 我有很多细节。 I want to stack them within an array, can I do that?
我想将它们堆叠在一个数组中,可以吗?
detailObj = {
textDetail: "hello this is my text!",
id: "tooltip_businessDetails"
};
var idArray[0] = detailObg;
Yes: 是:
var idArray = [
{
textDetail: "hello this is my text!",
id: "tooltip_businessDetails"
},
{
textDetail: "another",
id: "anotherid"
},
// ...and so on
];
Or if you already have variables pointing at them: 或者,如果您已经有指向它们的变量:
var idArray = [detailObj, anotherDetailObj, yetAnotherDetailObj];
You can also do it dynamically after array creation: 您还可以在创建数组后动态地执行此操作:
var idArray = [];
idArray.push(detailObj);
idArray.push({
textDetail: "another",
id: "anotherid"
});
idArray.push(yetAnotheretailObj);
And you can do it the way you tried to, just with a slight change: 只需稍作更改,就可以按照您尝试的方式进行操作:
var idArray = [];
idArray[0] = detailObj;
idArray[1] = anotherDetailObj;
Any time you set an array element, the array's length
property is updated to be one greater than the element you set if it isn't already (so if you set idArray[2]
, length
becomes 3
). 任何时候设置数组元素时,数组的
length
属性都会更新为比设置的元素大一个(如果尚未设置)(因此,如果设置idArray[2]
,则length
3
)。
Note that JavaScript arrays are sparse , so you can assign to idArray[52]
without creating entries for 0
through 51
. 请注意,JavaScript数组是稀疏的 ,因此您可以分配给
idArray[52]
而不创建0
到51
条目。 In fact, JavaScript arrays aren't really arrays at all . 实际上,JavaScript数组根本不是数组 。
instead of doing this thing use below code 而不是这样做,请使用以下代码
var arr = [];
arr.push(detailobj);
You can use object-oriented approach: 您可以使用面向对象的方法:
var detail = function(id, text) {
this.id = id;
this.text = text;
};
var arr = [];
arr.push(new detail("myid", "mytext"));
console.log(arr);
I want to stack them within an array, can I do that ?
我想将它们堆叠在一个数组中,可以吗?
Yes you can do that. 是的,你可以这么做。 Array in JavaScript are flexible and can hold objects as well.
JavaScript中的数组非常灵活,并且可以容纳对象。
Example: 例:
var myArr = [];
myArr.push(detailObj);
例如:
var idArray = [detailObj1, detailObj2];
Another one : 另一个 :
var myArray = new Array();
myArray.push(<your object>)
detailObj = {
textDetail: "hello this is my text!",
id: "tooltip_businessDetails"
};
var array = [];
for(var key in detailObj) {
array.push(detailObj[key]);
}
alert(array[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.