javascript对象的循环属性

loop properties of javascript object

本文关键字:属性 循环 对象 javascript      更新时间:2023-09-26

我有一个函数,循环所有的对象属性,并返回值,如果它符合一定的条件

基本上我就是这样做的

  //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

,这里是一个工作小提琴:http://jsfiddle.net/LVc6G/

,这里是小提琴的代码:

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