javascript - 没有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
是一种不好的做法,所以我应该如何进行?
非常感谢
解决方案
像这样的东西会起作用:
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);
}
}
推荐阅读
- angular - 在传单 on("click", function()) 操作后打开 Angular Material 对话框
- amazon-web-services - 获取 aws rds 快照的本地副本
- tfs - TFS (Azure DevOps) 通知 - 发送通知以开始发布部署
- kubernetes - 如何将请求超时从 helm 传递到 kubectl
- vb.net - 将委托作为对象属性传递
- eclipse - testng.xml 文件 - testNG 项目通过 IDE eclipse 正常工作/运行,但不是通过 cmd 提示符
- c++ - 在 Visual Studio 的路径中,后跟两个点的双反斜杠是什么意思
- python - 更新由 sudo 命令安装的 python 包
- c# - 与 HID 兼容设备通信
- python - 如何解决传递依赖 google-resumable-media 的版本不兼容问题?