Javascript循环从数组中获取动态变量(和值),而无需评估

时间:2018-07-26 13:54:09

标签: javascript variables eval

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

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是一个不好的做法,所以我应该如何进行?

非常感谢

2 个答案:

答案 0 :(得分:1)

类似的事情会起作用:

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


        }
    }

答案 1 :(得分:0)

为什么不使用函数?

const getStyle = (horizontal, vertical) => ({
  position: 'absolute',
  xPercent: horizontal === 'left' ? 0 : horizontal === 'center' ? -50 : -100,
  yPercent: vertical === 'top' ? 0 : vertical === 'center' ? -50 : -100,
  left: horizontal === 'left' ? '0%' : horizontal === 'center' ? '50%' : '100%',
  top: vertical === 'top' ? '0%' : vertical === 'center' ? '50%' : '100%'
});

const left_top = getStyle('left', 'top');
const left_bottom = getStyle('left', 'bottom')
const center_center = getStyle('center', 'center');
// etc.
console.log(left_top, left_bottom, center_center);

请注意,任何意外的值都会回退到右/底。