在“对象”中预设选项,并查看它是否没有'在允许的属性中不存在
Preset Options in Object and see if it doesn't exist in allowed properties
我正在尝试为对象列表中允许的选项创建一个预设列表。这是代码
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?
});
您可以对照一组允许的选项检查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'
});
现在您可以看到,extra
在a
中根本没有使用,尽管它是作为参数传递给a
的匿名对象的属性。此外,传递给a
的所有参数都是垃圾收集的,除非您不打算创建闭包,即从a
返回本地值或函数。
相关文章:
- 查找数组's按属性不存在于另一个数组中的对象
- 错误 TS2339:类型“{}”上不存在属性“forEach”
- Express和Typescript-Error.stack和Error.status属性不存在
- 在'用于'如果javascript中不存在对象属性,则循环
- Realm React Native-需要迁移:目标类型'字符串'不会'不存在于属性'电
- 有没有一个lodash函数可以合并两个对象并删除其中一个对象的属性(如果它们没有)'不存在于另一个中
- Javascript:当属性可能不存在时,在对象中使用OR条件
- Javascript for ..有时通过不存在的属性
- 如何在访问 JavaScript 对象的不存在属性时抛出错误
- TypeScript 工厂模式说属性不存在
- 如果属性不存在,则不显示对象的数据
- 错误“属性'日期选择器'在带有打字稿的类型'IAugmentedJQuery'上不存在
- 将不存在的属性的引用分配给变量
- 为什么在 JavaScript 中引用对象的不存在属性不会返回引用错误
- 打字稿 - 为什么猫鼬中不存在“方法”属性
- 可以按不存在的属性对数组进行角度过滤
- 属性在打字稿接口上不存在
- Spring复选框选中的属性不存在
- 解决打字错误的最佳方法-类型上不存在属性
- TypeScript - 类型“节点”上不存在属性“id”