0

我正在尝试制作我的对象列表中允许的选项的预设列表。这是代码

var a = function(cmd, options){
     var objList = [options.search ,options.demand];

    if(!(options in objList)){
      console.warn('Not an Allowed * in the options Property');
      }
 }; 

还是我应该做

var a = function(cmd, options){
     var objList = [search , demand];

    if(!(options in objList)){
      console.warn('Not an Allowed option in the options Property');
      }
 }; 

基本上我想要做的是设置它search并且demand是选项属性中允许的选项,所以比可以做的晚

 a('cmd',{
  search:'',
  demand:function() {
   alert('Hello');
    },
  //warn that the next option is not allowed
  quote: function() {
    alert('quote of user');
   }
  });

如果您无法理解我的要求,请询问,我会尽力解释更多。

也许这样写会更好?

var a = function(cmd, options){
  options = {
   theme: function(color) {
    $('body').css('backgroundColor',color);
    },
   color:''
   };
 };

a('cmd',{
  theme:'#000'//though this is not working?
 });
4

2 回答 2

2

options您可以根据一系列允许的选项检查每个属性,如下所示:

var a = function(cmd, options){
  var allowedOptions = ["search", "demand"];

  var hasDisallowedOptions = false;

  for (option in options) {
    if(allowedOptions.indexOf(option) === -1 ) {
      hasDisallowedOptions = true;
      break;
    }
  }

  // if hasDisallowedOptions is true, then there is a disallowed option
};

带有几个测试用例/示例的 jsfiddle

于 2013-07-21T22:26:32.383 回答
1

在对象中传递参数的一个想法是,它允许您选择要在函数中使用的参数,您可以简单地忽略options对象中的额外属性。因此,您也不需要“过滤”参数的属性。

假设您有这样的功能:

var a = function (cmd, options) {
    var theme = {
        backgroundColor: options.bgColor,
        color: options.color
    }
    // Do something with theme
    // Notice also, that there was no use for options.extra in this function
}

然后你像这样调用a

a('cmd', {
    bgColor: '#ff0',
    color: '#000',
    extra: 'This is an extra property'
});

现在您可以看到,extra它根本没有被使用a,尽管它是a作为参数传递给的匿名对象的属性。此外,所有传递给的参数a都是垃圾收集的,除非您不打算创建闭包,即从a.

于 2013-07-21T23:22:51.573 回答