我有一个函数,可以循环所有对象属性,并在满足特定条件时返回值
基本上这就是我正在做的
//an enum
var BillingType = Object.freeze({
PayMonthly: { key: 'Monthly', value: 1 },
PayYearly: { key: 'Yearly', value: 2 }
});
现在为了让它工作,我这样做
for (var property in BillingType ) {
if (BillingType .hasOwnProperty(property)) {
if (value === BillingType [property].value) {
return BillingType [property].key;
}
}
}
它工作正常,但为了使其对所有枚举通用,我将代码更改为
getValue = function (value, object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (value === object[property].value) {
return object[property].key;
}
}
}
}
现在当我尝试从其他函数调用
enumService.getValue(1, 'BillingModel');
而不是循环所有属性,而是在其字符上开始循环。
我如何将字符串转换为对象,或者我这样做完全错误。任何帮助将不胜感激
问候
最佳答案
你的getValue
看起来不错,只需使用调用它即可
enumService.getValue(1, BillingModel); // <-- no quotes
这是一个工作 fiddle :http://jsfiddle.net/LVc6G/
这是 fiddle 的代码:
var BillingType = Object.freeze({
PayMonthly: { key: 'Monthly', value: 1 },
PayYearly: { key: 'Yearly', value: 2 }
});
var getValue = function (value, object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (value === object[property].value) {
return object[property].key;
}
}
}
};
alert(getValue(1, BillingType));
关于javascript - javascript 对象的循环属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927194/