带有几个参数的JavaScript对象

时间:2013-06-06 18:58:38

标签: javascript jquery

目标

我想创建一个具有以下参数的函数:

MyObject.calculateResponsiveHeights({
    containers: {
        ".content",
        ".sidebar"
    },
    spacing: {
        125, // This will be attributed to ".content"
        240 // This will be attributed to ".sidebar"
    }
});

问题

我不知道怎么做。

我现在拥有的(功能实现 - 只是为了了解情况)

function calculateResponsiveMeasures() {
    var containerContentResponsiveHeight = $(window).height() - 185,
        sidebarProductsSummaryResponsiveHeight = $(window).height() - 255;

    containerContentResponsiveHeight = containerContentResponsiveHeight + "px";
    sidebarProductsSummaryResponsiveHeight = sidebarProductsSummaryResponsiveHeight + "px";

    $(".container-content").css("height", containerContentResponsiveHeight);
    $(".products-summary").css("height", sidebarProductsSummaryResponsiveHeight);
}

是的,那太恶心了,是吗?

观察

我不是要求改进我的代码,也不是说它是更好还是更坏的方式 - 我只是想更好地组织我的功能。

干杯!

1 个答案:

答案 0 :(得分:3)

您正在尝试创建数组[1, 2, 3]

但是,您应该使用单个对象:

{
    ".content": 125,
    ".sidebar": 240
}

然后,您可以使用for in loop迭代属性。