[英]Javascript Newb : How do I instantiate a var as “blah.1” and “blah.2”?
I currently have a block like this defining some vars 我目前有一个这样的块定义一些变量
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this: 带有ID的func是这样的:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit. 我正在尝试重构。
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like 我在想,如果可以的话,可以用点而不是下划线来实例化变量
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication. 那么我将能够更好地利用已经传递到函数中的ID并消除大量重复。
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale;
我希望通过单次调用
slider.id.x.baseVal.value = x/scale;
来简化功能slider.id.x.baseVal.value = x/scale;
rather than having to have that code in each of the IF/ELSE conditions. 而不是必须在每个 IF / ELSE条件中都使用该代码。
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ". 但是,当我尝试这样做时,出现错误消息“ Uncaught SyntaxError:Unexpected number ”。
How should this be done? 应该怎么做?
You can't use a plain numeric key in an object. 您不能在对象中使用纯数字键。
You can do this, though: 您可以执行以下操作:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token. 此外,如果键实际上是变量而不是文字标记,则不允许使用您建议的语法。
In your example slider.id
actually refers to the object with literal key id
, not whatever value the variable id
happens to have. 在您的示例中,
slider.id
实际上是指具有文字键 id
的对象,而不是变量 id
碰巧具有的任何值。
You have to put the variable inside square brackets, ie slider[id]
, so your function would be written thus: 您必须将变量放在方括号内,即
slider[id]
,因此您的函数应这样编写:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. 你不能 The
.
的
.
is an invalid character for a variable identifier. 是变量标识符的无效字符。
You can use it in object properties though. 不过,您可以在对象属性中使用它。
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property. 然后使用成员运算符的方括号版本访问属性。
alert( sliders["slider.1"].id );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.