【发布时间】:2016-04-15 14:55:55
【问题描述】:
我正在尝试在 Angular 服务中扩展 js 原生数组以添加一些额外的功能,而无需对全局对象进行原型设计。
app.factory('Collection', function($http, $q) {
var Collection = function(arr) {
this.key = 'id';
this._last = 0;
this._first = 77777777; //just big number.
this.append(arr);
}
Collection.prototype = new Array;
Collection.prototype.orderBy = function(n, reverse) {
if (reverse) {
this.sort(function(a, b) {
return b[n] - a[n];
})
} else {
this.sort(function(a, b) {
return a[n] - b[n];
})
}
}
Collection.prototype.spliceBy = function(key, val) {
for (var i = 0; i < this.length; i++) {
if (this[i][key] !== val) {
this.splice(i, 1); ///THIS NEVER HAPPENS !!
console.log('removed ' + i + ' from ', this);
}
}
}
Collection.prototype.subset = function(key, val) {
return this.filter(function(v) {
return (v[key] === val);
});
}
Collection.prototype.add = function(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i][this.key] > this._last) {
this._last = this[i][this.key];
}
if (this[i][this.key] < this._first) {
this._first = this[i][this.key];
}
if (this[i][this.key] === data[this.key]) {
if (override) {
this[i] = data;
console.log('updated uniquePush');
}
return i;
break;
}
}
var id = this.push(data) - 1;
data._index = id;
return id;
}
return collection
});
除了spliceBy 函数外,这一切正常。
我需要过滤掉没有 value = x; 的元素
例如在我的控制器中
.controller(function($scope,Collection){
$scope.posts = new Collection;
$scope.posts.add({id:1,type:'post'});
$scope.posts.add({id:2,type:'comment'});
//Collection is now [{id:1,type:post},{id:2,type:comment}];
//i want to remove all comments from array
$scope.posts.spliceBy('type','comment');
});
调用 spliceBy 时没有任何反应:*(
【问题讨论】:
-
这看起来不对
Collection.prototype = new Array;。你不能在 ES5 中做到这一点。不过,您可以在 ES6 中对数组进行子类化。 -
@elclanrs 对此不确定,但它在我所有的浏览器和科尔多瓦应用程序中都能正常工作:-)
-
如果它工作正常,你为什么要发布这个问题?除了最新版本的 Chrome/Edge(还没有 FF),甚至要求使用(本机)类语法,数组不可子类化。使其工作的唯一(我的意思是唯一的)其他方法是编写一个带有内部数组实例的包装类,它根据需要委托给它或猴子补丁 Array.prototype。一旦您尝试在您的“子类”上调用本机数组方法(例如 splice、reduce、shift),它就会失败。
-
我知道,因为我尝试在地图上做同样的事情stackoverflow.com/questions/28900954/…
标签: javascript arrays angularjs prototype-pattern