首页 > 解决方案 > 没有eval的数组中动态变量(和值)的Javascript循环

问题描述

我想缩短我的代码,这是我想要生成的:

left_top = {position:"absolute", xPercent:0, yPercent:0, left:"0%", top:"0%"};
left_center = {position:"absolute", xPercent:0, yPercent:-50, left:"0%", top:"50%"};
left_bottom = {position:"absolute", xPercent:0, yPercent:-100, left:"0%", top:"100%"};

center_top = {position:"absolute", xPercent:-50, yPercent:0, left:"50%", top:"0%"};
center_center = {position:"absolute", xPercent:-50, yPercent:-50, left:"50%", top:"50%"};
center_bottom = {position:"absolute", xPercent:-50, yPercent:-100, left:"50%", top:"100%"};

right_top = {position:"absolute", xPercent:-100, yPercent:0, left:"100%", top:"0%"};
right_center = {position:"absolute", xPercent:-100, yPercent:-50, left:"100%", top:"50%"};
right_bottom = {position:"absolute", xPercent:-100, yPercent:-100, left:"100%", top:"100%"};

这就是我的做法:

var output="";
xPos = ["left", "center", "right"];
yPos = ["top", "center", "bottom"];

for (i=0;i<=2;i++){
    xVal = 50*i;
    for(j=0;j<=2;j++){
        yVal = 50*j;
        eval( xPos[i] + "_" + yPos[j] + " = {position:'absolute', xPercent:" + (-xVal) + ", yPercent:" + (-yVal) + ", left:'" + xVal + "%', top:'" + yVal + "%'}");

    }
}

我知道这eval是一种不好的做法,所以我应该如何进行?

非常感谢

标签: javascriptvariableseval

解决方案


像这样的东西会起作用:

    var output = "";
    xPos = ["left", "center", "right"];
    yPos = ["top", "center", "bottom"];

    var getObj = function (x, y) {
        return { position: "absolute", xPercent: x * - 1, yPercent: y * -1, left: x + '%', top: y + '%' };
    }

    var results = {};

    for (i = 0; i <= 2; i++) {
        xVal = 50 * i;
        for (j = 0; j <= 2; j++) {
            yVal = 50 * j;
            var key = xPos[i] + "_" + yPos[j];
            var obj = getObj(xVal, yVal);
            results[key] = getObj(xVal, yVal);


        }
    }

推荐阅读