在“对象”中预设选项,并查看它是否没有'在允许的属性中不存在

Preset Options in Object and see if it doesn't exist in allowed properties

本文关键字:不存在 属性 是否 对象 选项      更新时间:2023-09-26

我正在尝试为对象列表中允许的选项创建一个预设列表。这是代码

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

基本上,我想做的是在选项属性中设置searchdemand是允许的选项,以便稍后可以进行

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

您可以对照一组允许的选项检查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与几个测试用例/示例

在对象中传递参数的一个想法是,它允许您选择要在函数中使用的参数,您可以简单地忽略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'
});

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