是否有任何内置方法可以将 JavaScript 对象的属性更改为某个值?



我想将JavaScript对象的所有属性值更改为某个值(在这种情况下为false)。我知道如何通过单独更改它们(示例A)或使用循环(示例B)来做到这一点。我想知道是否有其他内置方法可以做到这一点,推荐的方法是什么(主要是在速度方面,或者是否有其他副作用)?

伪码:

// Example object
Settings = function() {
    this.A = false;
    this.B = false;
    this.C = false;
    // more settings...
}
// Example A - currently working
updateSettingsExampleA = function(settings) {
    // Settings' properties may not be be false when called
    settings.A = false;
    settings.B = false;
    settings.C = false;
    while (!(settings.A && settings.B && settings.C) && endingCondition) {
        // code for altering settings
    }
}
// Example B - currently working
updateSettingsExampleB = function(settings) {
    // Settings' properties may not be be false when called
    for (var property in settings) {
        settings[property] = false;
    }
    while (!(settings.A && settings.B && settings.C) && endingCondition) {
        // code for altering settings
    }
}
// possible other built in method
updateSettingsGoal = function() {
    this.* = false; // <-- statement to change all values to false
    while (!(this.A && this.B && this.C) && endingCondition) {
        // code for altering settings
    }
}
不,没有这样的内置方法。如果你想"将所有属性值更改为false",那么使用循环来完成。你的例子B完全可以。

我不建议展开循环(示例A),除非它不是"所有属性",或者您需要这个片段的绝对最大速度。但这只是一个微观优化,它不会让你的代码变得更好。

最新更新