1

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;
4

7 回答 7

7

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).

Note that JavaScript arrays are sparse, so you can assign to idArray[52] without creating entries for 0 through 51. In fact, JavaScript arrays aren't really arrays at all.

于 2012-06-19T14:26:44.363 回答
3

instead of doing this thing use below code

var arr = [];

arr.push(detailobj);
于 2012-06-19T14:26:46.933 回答
2

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);
于 2012-06-19T14:27:39.833 回答
0

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.

Example:

var myArr = [];
myArr.push(detailObj);
于 2012-06-19T14:26:12.767 回答
0

for example:

var idArray = [detailObj1, detailObj2];
于 2012-06-19T14:26:37.840 回答
0

Another one :

var myArray = new Array();
myArray.push(<your object>)
于 2012-06-19T14:28:46.553 回答
0
detailObj = {

    textDetail: "hello this is my text!",
    id: "tooltip_businessDetails"

};

var array = [];
for(var key in detailObj) {
   array.push(detailObj[key]);
}
alert(array[0]);
于 2012-06-19T14:29:01.003 回答