简体   繁体   中英

javascript iterate array of variables and reassign value to each variable

Hi how should i iterate array of variables and reassign value to each variable. Eg 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.

In a function scope, you can get a list of arguments using the implicit variable arguments :

function foo(param1, param2, param3) {
   for(var i = 0; i < 3; i++) {
      if(typeof arguments[i] == 'undefined') {
         arguments[i] = 0;
      }
   }
}

http://jsfiddle.net/CTKRH/1/

Well, you could do it like this, but that would only change the value inside the array, and not the original var.

var defaultValue = 5;
var var1 = 1;
var var2 = 2;
var var3 = null;
var arr = [var1, var2, var3];

for(var i = 0, l = arr.length; i < l; i++) {
    if(!arr[i]) {
        arr[i] = defaultValue;
    }
}

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

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