以编程方式在javascript中选择对象的属性

时间:2014-01-13 22:46:39

标签: javascript attributes

当我用date_narrow(pdb, "datepub", "1980", "2000")调用此函数时,我希望返回的计数为2,而pdb [0] .selected设置为false。相反,我的调试器显示arr [k] .dfield总是未定义,而我希望它是pdb [k] .datepub。也就是说,我试图在运行时选择对象arr [k]的属性。有关如何正确执行此操作的任何建议吗?

var date_narrow = function (arr, dfield, earlier_date, later_date) {
    var count = 0;
    for (var k = 0; k < arr.length; k++) {
        if (arr[k].selected) {
            // following are string comparisons
            if ((arr[k].dfield < earlier_date) || (arr[k].dfield > later_date)) {
                arr[k].selected = false;
            } else {
                count = count + 1;
            }
        }
    }
    return (count);
};

pdb = [{
    datepub: "2012",
    selected: true
}, {
    datepub: "1999",
    selected: true
}, {
    datepub: "1980",
    selected: true
}];

1 个答案:

答案 0 :(得分:2)

在JavaScript中,数组语法(obj[...])也适用于按名称访问对象的属性:

var date_narrow = function (arr, dfield, earlier_date, later_date) {
    var count = 0;
    for (var k = 0; k < arr.length; k++) {
        if (arr[k].selected) {
            // following are string comparisons
            if ((arr[k][dfield] < earlier_date) || (arr[k][dfield] > later_date)) {
                arr[k].selected = false;
            } else {
                count = count + 1;
            }
        }
    }
    return (count);
};

Demonstration