我有一个方法,它接受一个对象作为参数,并且需要所有预期的属性,否则我想抛出错误。这样做的最佳实践是什么。用Underscore的_.map
可以轻松完成吗或者类似的东西?
我所说的“必需”不是null
和undefined
.
最佳答案
您可以使用_.intersection
和Object.keys
:
function yourFunc(args) {
if(_.intersection(["name", "secondName", "age"], Object.keys(args)).length != 3) {
throw Error("Check your arguments: something is missing!");
}
}
请注意,如果参数不是从原型(prototype)实例化的,这种检查将会起作用。 From Mozilla Development network :
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
关于javascript - 如何检查对象属性是否已在用户提供的参数中设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23323439/