views:

59

answers:

2

Hi how should i iterate array of variables and reassign value to each variable. E.g in jQuery

function test(param1, param2) {

  $.each([param1, param2], function (i, v) {
     //check if all the input params have value, else assign the default value to it
     if (!v) 
         v = default_value; //this is wrong, can't use v, which is value
  }

}

How should I get the variable and assign new value in the loop?

Thank you very much!


Maybe I didn't describe my question clearly. My intention is to iterate array of variables, not array of strings.

var variable_1 = "hello";
var variable_2 = null;

i want to iterate [variable_1, variable_2], and check each value, if variable_2 is null, so i will assign the default value to variable_2 to change the value.

A: 

Just use JavaScript, you don't need jQuery for this:

var ​myarray = ['hello', null];​​
var i;
var default_value = 'default';

for (i = 0; i < myarray.length; i++) {
    if (! myarray[i]) {
        myarray[i] = default_value;
    }
}

alert(myarray);
Skilldrick
Maybe I didn't describe my question clearly. My intention is to iterate array of variables, not array of strings.var variable_1 = "hello";var variable_2 = null;i want to iterate [variable_1, variable_2], and check each value, if variable_2 is null, so i will assign the default value to variable_2 to change the value.
Shanison
A: 

you can iterate over the array like this

var arrValues = [ "one", "two", "three" ];
var array2   = [ "one", "two", "three" ];
// Loop over each value in the array.
$.each(
arrValues,
function( intIndex, objValue ){
     objValue =array2 [intIndex];  
}
);
Pranay Rana
Maybe I didn't describe my question clearly. My intention is to iterate array of variables, not array of strings.var variable_1 = "hello";var variable_2 = null;i want to iterate [variable_1, variable_2], and check each value, if variable_2 is null, so i will assign the default value to variable_2 to change the value.
Shanison