$$ var (in php) Equivalent in javascript

I have a variable var commision_1 = 2000 ;var commision_2 = 4000;

and a function:

function updateCommission(period){
    $("input:text[name='commission']").val('commision_'+period);
}

      

I would like if the period is 1 then the textbox value should be 2000; I know I can use arrays, but I am working on another user's code, is there any way to get around it like in php as I wrote$x = 'commision_' .$period; echo $$x;

+3


source to share


2 answers


You can use square notation to get variables.

Provided these variables are defined in the window area:



function updateCommission(period){
    $("input:text[name='commission']").val(window['commision_' + period]);
}

      

Having said that, defining numbered variables (up to 2000 ..!?) Is not a good idea. An array was created for this purpose. My best answer would be to request that these variables be overwritten as an array, but I realize this is often easier said than done.

+5


source


var commission_1 = 2000, commission_2 = 4000;
var name = 'commission_1';
console.log(window[name]);

      



0


source







All Articles