简体   繁体   中英

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:

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.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.

When I try that though, I get an error saying " 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.

You have to put the variable inside square brackets, ie slider[id] , so your function would be written thus:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM