简体   繁体   English

如何使用forEach在JavaScript和jQuery中设置动态变量?

[英]How can I use forEach to set dynamic variables in JavaScript and jQuery?

I am writing a jQuery plugin. 我正在写一个jQuery插件。 There is an object of options that I want to loop through to set regular variables with. 我想遍历选项对象以设置常规变量。 It would basically set a variable that would be the index of the object item. 它基本上将设置一个变量,该变量将成为对象项的索引。 I want to determine if any options are left blank and if they are, set the regular variable to the default value. 我想确定是否将任何选项留为空白,如果将它们设置为默认值,则将常规变量设置为默认值。 I would usually use the following to set options to a default if they are blank: 如果空白,我通常会使用以下内容将选项设置为默认值:

 var defaults = {
     someVar1 : "somevar1",
      omeVar2:  "somevar2"
 };

var someVar1;
var someVar2;

function init(options, defaults){
   if(typeof options.someVar1 === 'undefined'){
      someVar1 = defaults.someVar1;
   } else {
      someVar1 = options.someVar1;
  }
   return something();
}
function something(){
   console.log(item);
});

This can be a big pain in the butt if I have a lot of options to set. 如果我要设置的选项很多,这可能是一个很大的麻烦。 How could I modify my code below to dynamically define global variables? 如何修改下面的代码以动态定义全局变量?

function init(element, options){
    $(document).ready(function(){
         $.each(options, function(index, value){
             if(typeof options.index === 'undefined'){

              }
         });
     });
 }

Lets say you have an object : 假设您有一个对象:

var my_object = {
    item1 : 1,
    item2 : 2,
    item3 : 3,
}

var i;
for(i in my_object){
    console.log(i); 
    console.log(my_object[i]);
}
/*
    This will print in the console:
    item1
    1
    item2
    2
    item3
    3
*/

for each will not find an undefined, because undefined does not exist, unless your object is like this: 对于每个对象,将找不到一个未定义的对象,因为未定义的对象不存在,除非您的对象是这样的:

var my_object = {
    item1 : 1,
    item2 : 2,
    item3 : 3,
    item4 : undefined
}

Also : 另外:

$.each(options, function(index, value){
  // if(typeof options.index === 'undefined'){ <-- this is wrong
     if(typeof options[index]=== 'undefined'){ <-- this is correct
        // Also you have the value, why not "value === undefined" ?
     }
});

It sounds like you might want to setup a predefined variable array then based on your index of the option read its default value 听起来您可能想设置一个预定义的变量数组,然后根据选项的索引读取其默认值

var optionDefaults = ["val1", "val2", "val3"];
function init(element, options){
    $(document).ready(function(){
         $.each(options, function(index, value){
             if(typeof options.index === 'undefined'){
                  var optiondefValue = optionDefaults[index];
                  //do whatever you want here.
              }
         });
     });
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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