繁体   English   中英

javascript数组原型-添加了新方法-奇怪的console.log

[英]javascript array prototype - new method added - strange console.log

我正在一个项目中,其中Array原型添加了新方法:

Array.prototype.addOrRemove = function(value) {
    var index = _.indexOf(this, value);

    if (index === -1) {
        this.push(value);
    } else {
        this.splice(index, 1);
    }
    return this;
};

它要么添加新值(如果数组中不存在该值),要么将其删除(否则)。 奇怪的是,当我键入:

console.log([]);

我得到以下输出(在chrome JS控制台中):

[addOrRemove: function]

我认为在这样的控制台日志中应该只有值。 我做错了还是正常行为(无论如何似乎很奇怪)? 我希望能得到一些解释。

您可以使用defineProperty ,默认情况下,该属性使属性不可枚举。

Object.defineProperty(
    Array.prototype,
    'addOrRemove',
    {
        get: function() {
            return function(value) {
                var index = _.indexOf(this, value);

                if (index === -1) {
                    this.push(value);
                } else {
                    this.splice(index, 1);
                }
                return this;
            };
        }
    }
);

console.log([]);

http://jsfiddle.net/qHFhw/1/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM