在我的代码中,我有一长串的全局变量,它们都以相同的值开始,但是独立地变化。有没有一种方法可以将它们组合在一起,而不是使用30行来定义它们? (特别是所有y值)
var cx1 = 0,
cx2 = 100,
cx3 = 200,
cx4 = 300,
cx5 = 400,
cx6 = 500,
cx7 = 600,
cx8 = 700,
cx9 = 800,
cx10 = 900,
cy = 100,
y1 = 315,
y2 = 685,
y12 = 315,
y22 = 685,
y13 = 315,
y23 = 685,
y14 = 315,
y24 = 684,
y15 = 315,
y25 = 685,
y16 = 315,
y26 = 685,
y17 = 315,
y27 = 685,
y18 = 315,
y28 = 685,
y19 = 315,
y29 = 685,
y110 = 315,
y220 = 685,
endx,
endy;
答案 0 :(得分:1)
(特别是所有y值)
由于偶数y值都是315而奇数值都是685,你可以自己构建一个数组:
var y = [];
for (var i = 0; i < 28; ++i) {
y[i] = i % 2 === 0 ? 315 : 685;
}
// Then you refer to them by index
console.log(y[0]); // 315
y[0] = 320;
console.log(y[0]); // 320
&#13;
如果您能够使用您正在使用的奇数系列数字(15,25,110等)来引用y
值非常重要,那么您可以制作它们是对象属性:
var y = Object.create(null);
[1, 2, 12, 22, 23, 14, 24, 15, 25, 16, 26, 17, 27, 18, 28, 19, 29, 110, 220].forEach(function(value, index) {
y[value] = index % 2 === 0 ? 315 : 685;
});
console.log(y[22]); // 685
y[22] = 670;
console.log(y[22]); // 670
&#13;
在ES2015 +中,您可以改为使用Map
:
const y = new Map();
[1, 2, 12, 22, 23, 14, 24, 15, 25, 16, 26, 17, 27, 18, 28, 19, 29, 110, 220].forEach((value, index) => {
y.set(value, index % 2 === 0 ? 315 : 685);
});
console.log(y.get(22)); // 685
y.set(22, 670);
console.log(y.get(22)); // 670
&#13;
答案 1 :(得分:0)
而不是数千个变量可能使用一个数组:
var y = [undefined, 315, 685,/*...*/];
或者重复:
var y=",315,685".repeat(10).split(",").slice(1);
然后访问:
y[1]; //instead of y1
或者使用对象(如果数组中的空格多于值):
var y = {
1:315,
2:685,
12:315,
22:685,
13:315,
23:685,
14:315,
24:684,
15:315,
25:685,
16:315,
26:685,
17:315,
27:685,
18:315,
28:685,
19:315,
29:685,
110:315,
220:685
};
如果你真的想以错误的方式做到这一点,拿上面的对象/数组并将其复制到窗口中:
Object.keys(y)/* or just y for the array way*/.forEach(function(key){
window["y"+key]=y[key];
});
alert(y1);
答案 2 :(得分:0)
数组和对象。
cx = [0,100,200,300];
cy = [100];
y = {
1: 315,
2: 685,
110: 315
}
// etc.
//to use
cx[0] == 0
cx[1] == 100
y['1'] == 315
y['110'] == 315
答案 3 :(得分:0)
可能要到这个可以完成。之后我们添加了一些逻辑来清理0
。
var vals = [315, 685];
var arr = {};
for (var j = 0; j < 12; j++) {
for (var i = 1; i <= vals.length; i++) {
var key = (j % 10 == 0) ? i : '' + i + j;
arr['y' + key] = vals[i - 1];
}
}
console.log(arr);