如何将所有对象项定义/重置为零

时间:2014-12-07 22:15:09

标签: javascript

我需要启动一个像我在下面的对象。是否有更简单的方法来初始化它并定期重置它以使所有值都为0,或者只是使用for循环的情况?

var vote_tally = {};
vote_tally[1]=0;
vote_tally[2]=0;
vote_tally[3]=0;
vote_tally[4]=0;

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

您可以通过提供构造函数并添加到其原型来实现此目的。

function MyObject(value) {
    value = value || 0;
    this[1] = value;
    this[2] = value;
    this[3] = value;
    this[4] = value;
}

MyObject.prototype.reset = function (value) {
    value = value || 0;
    for (var key in this) {
        if (this.hasOwnProperty(key)) {
            this[key] = value;
        }
    }
};

var o = new MyObject();
o['1'] = 42;
o.reset();
console.log();
// {1:0,2:0,3:0}

如果要创建任意长度的数组并将所有值初始化为0.可以这样做。

function initArray(size, value) {
    value = value || 0;
    return Array.apply(0, Array(size)).map(function() {return value;});
}

var a = initArray(10);
console.log(a);
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

var b = initArray(10, 1);
console.log(b);
// [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

如果要重置阵列的所有值,可以执行此操作。但是,修改JavaScript内置原型并不是一个好习惯。

Array.prototype._reset = function (value) {
    value = value || 0;
    for (var i = 0; i < this.length; i += 1) {
        this[i] = value;
    }
};

b._reset();
console.log(b);
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

答案 1 :(得分:-1)

您可以像这样实例化一个数组:

var array = [0, 0, 0];

对象:

var object = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

要清空它,您只需写下:array = []

但请解释一下你正在尝试做什么,因为你可能从错误的角度接近这个。

相关问题