1

我有两个 JavaScript 对象:

var attributes1 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/HtmlLibrary.css"      
};
var attributes2 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/jquery.contextMenu.css"       
};

我有什么方法可以将这两个对象组合成一个具有两个子对象(关联数组)的对象?我想遍历它并每次获取一组属性?

谢谢

4

3 回答 3

3

是的,那些不是数组,但你可以有对象数组,我认为你正在寻找的是:

var attributes = [
                  {
                   "type": "text/css", 
                   "rel": "stylesheet",
                   "href": baseUrl + "Styles/HtmlLibrary.css"      
                  },
                  {
                   "type": "text/css",
                   "rel": "stylesheet",
                   "href": baseUrl + "Styles/jquery.contextMenu.css"       
                  }];
于 2012-07-04T06:14:51.623 回答
3

是的,您可以轻松做到这一点:-

var baseUrl="www.google.com" // Base URL just for the sake of program.
var attributes = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/HtmlLibrary.css"      
};
var attributes1 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/jquery.contextMenu.css"       
};
var k=[];
k.push(attributes);
k.push(attributes1)

    //Since K has both the associative arrays now you can refer using
    for(var i=0;i<k.length;i++)
        {
        console.log(k[i].type+" "+k[i].rel+" "+k[i].href)

        }

这是小提琴 URL http://jsfiddle.net/HSdJh/1/

于 2012-07-04T06:14:52.713 回答
1
var attributes1 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/HtmlLibrary.css"      
};
var attributes2 = {
    "type": "text/css",
    "rel": "stylesheet",
    "href": baseUrl + "Styles/jquery.contextMenu.css"       
};

var combined = {};

combined.attributes1 = attributes1;
combined.attributes2 = attributes2;


for(var attribute in combined){

    if(combined.hasOwnProperty(attribute)){
        console.log(attribute);
        console.log(combined[attribute]);
    }

}
于 2012-07-04T06:28:03.330 回答