开发者

javascript iterate array of variables and reassign value to each variable

开发者 https://www.devze.com 2023-01-04 06:37 出处:网络
Hi how should i iterate array of variables and reassign value to each variable. E.g in jQuery function test(param1, param2) {

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.


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


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号