我有一个对象(打算用作枚举),如下所示:
var CardEnum =
{
CA: 101,
C2: 102,
C3: 103,
C4: 104,
C5: 105,
C6: 106,
C7: 107,
C8: 108,
C9: 109,
C10: 110,
CJ: 111,
CQ: 112,
CK: 113,
DA: 201,
D2: 202,
D3: 203,
D4: 204,
D5: 205,
D6: 206,
D7: 207,
D8: 208,
D9: 209,
D10: 210,
DJ: 211,
DQ: 212,
DK: 213,
SA: 301,
S2: 302,
S3: 303,
S4: 304,
S5: 305,
S6: 306,
S7: 307,
S8: 308,
S9: 309,
S10: 310,
SJ: 311,
SQ: 312,
SK: 313,
HA: 401,
H2: 402,
H3: 403,
H4: 404,
H5: 405,
H6: 406,
H7: 407,
H8: 408,
H9: 409,
H10: 410,
HJ: 411,
HQ: 412,
HK: 413
};
我有这样的功能:
function myFunc(card)
{
if (card == null)
{
// throw exception
}
// do something with card
}
我打算像这样使用它:
myFunc(CardEnum.D7);
但是如果有人像这样使用它,我怎么能确保它抛出异常:
myFunc(170);
myFunc(103.5);
我必须检查传递的值是否是CardEnum对象的键值之一。如果不迭代CardEnum对象的所有键,有没有优雅的方法呢?
为了清楚,这没关系:
myFunc(311);
答案 0 :(得分:2)
您最安全的选择是改变您传递给该功能的内容 传递卡名称,而不是其值:
function myFunc(card) {
if (!CardEnum[card]) {
// throw exception
throw new Error('Invalid card passed to myFunc!');
}
// do something with card
}
而不是myFunc(CardEnum.D7);
,请致电myFunc('D7');
这样,用户不能只将任意值传递给函数。相反,你有将卡名称传递给函数,否则会引发错误。
如果您 允许0
作为值,则可以使用:
if (!CardEnum[card] != null) {
但是,我建议不要使用!= null
,因为这也允许其他假值传递,例如:''',false,NaN。
这将是一个更安全的选择:
if (!CardEnum[card] && CardEnum[card] !== 0) {
答案 1 :(得分:0)
尝试使用Object.hasOwnProperty()
var CardEnum = function() {
// object
this.card = {D7: 207};
this.myFunction = function(prop) {
// if `this.card` does not have property `prop`,
// passed as argument to `this.myFunction`,
// throw error
if (!this.card.hasOwnProperty(prop)) {
throw new Error(prop + " not found")
// else log `this.card[prop]` to `console`
} else {
console.log(this.card[prop])
}
};
};
// returns object containing `this.card` , `this.myFunction`
var card = new CardEnum();
// call `card.myFunction`
console.log(card.myFunction("D7"), card.myFunction("D123"))
var CardEnum = function() {
this.card = {
CA: 101,
C2: 102,
C3: 103,
C4: 104,
C5: 105,
C6: 106,
C7: 107,
C8: 108,
C9: 109,
C10: 110,
CJ: 111,
CQ: 112,
CK: 113,
DA: 201,
D2: 202,
D3: 203,
D4: 204,
D5: 205,
D6: 206,
D7: 207,
D8: 208,
D9: 209,
D10: 210,
DJ: 211,
DQ: 212,
DK: 213,
SA: 301,
S2: 302,
S3: 303,
S4: 304,
S5: 305,
S6: 306,
S7: 307,
S8: 308,
S9: 309,
S10: 310,
SJ: 311,
SQ: 312,
SK: 313,
HA: 401,
H2: 402,
H3: 403,
H4: 404,
H5: 405,
H6: 406,
H7: 407,
H8: 408,
H9: 409,
H10: 410,
HJ: 411,
HQ: 412,
HK: 413
};
this.myFunction = function(prop) {
if (!this.card.hasOwnProperty(prop)) {
throw new Error(prop + " not found")
} else {
console.log(this.card[prop])
}
};
};
var card = new CardEnum();
console.log(card.myFunction("D7"), card.myFunction("D123"))