【问题标题】:Array that can store only one type of object?只能存储一种对象的数组?
【发布时间】:2015-04-05 19:00:46
【问题描述】:

是否可以创建一个只允许某个对象存储在其中的数组?有没有一种方法可以将元素添加到我可以覆盖的数组中?

【问题讨论】:

  • 与其直接操作数组,不如创建您自己的函数或方法来操作数组,您可以在将数据实际放入数组之前根据需要调整数据。

标签: javascript


【解决方案1】:

是的,您可以,只需覆盖数组的 push 数组(假设您要存储的只是数字,而不是执行以下操作:

var myArr = [];
myArr.push = function(){
  for(var arg of arguments) {
    if(arg.constructor == Number) Array.prototype.push.call(this, arg);
  }
}

只需将Number 更改为您想要匹配的任何构造函数。此外,我可能会添加 and else 语句或其他内容,如果这是您想要的,则抛出错误。

更新:

使用 Object.observe(目前仅在 chrome 中可用):

var myArr = [];

Array.observe(myArr, function(changes) {
    for(var change of changes) {
        if(change.type == "update") {
            if(myArr[change.name].constructor !== Number) myArr.splice(change.name, 1);
        } else if(change.type == 'splice') {
            if(change.addedCount > 0) {
                if(myArr[change.index].constructor !== Number) myArr.splice(change.index, 1);
            }
        }
    }
});

现在在 ES6 中有代理,您应该能够执行以下操作:

var myArr = new Proxy([], {
    set(obj, prop, value) {
        if(value.constructor !== Number) {
            obj.splice(prop, 1);
        }
        //I belive thats it, there's probably more to it, yet because I don't use firefox or IE Technical preview I can't really tell you.
    }
});

【讨论】:

  • 但是当数组设置为 arr[3] = "not a number" 时这会起作用吗?
【解决方案2】:

不直接。但是您可以将数组隐藏在闭包中,只提供您的自定义 API 来访问它:

var myArray = (function() {
    var array = [];
    return {
        set: function(index, value) {
            /* Check if value is allowed */
            array[index] = value;
        },
        get: function(index) {
            return array[index];
        }
    };
})();

像这样使用它

myArray.set(123, 'abc');
myArray.get(123); // 'abc' (assuming it was allowed)

【讨论】:

  • 这是相当严格的,因为它不支持数组方法,例如.length.slice().forEach() 等...事实上,您甚至不能迭代该对象中的元素。展示了一个可能的方向,但在实施时可能不实用。
  • @jfriend00 是的,这些方法会非常有用。该实现留给读者作为练习:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多