0
我試圖在角度服務內部擴展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 =新的Array;'你不能這樣做,在ES5可以在ES6繼承陣列雖然 – elclanrs
@elclanrs不知道。關於那個但它在我的所有瀏覽器和科爾多瓦應用程序中都能正常工作:-) – Zalaboza
如果它的工作正常,您爲什麼要發佈這個問題?除了最新版本的Chrome/Edge(不支持FF),甚至需要使用(native)類語法之外,數組不可分。唯一的(也是我的意思是)使其工作的其他方法是編寫一個包裝類,它具有一個內部數組實例,它根據需要委派給它或者對Array.prototype進行monkey-patch。只要你嘗試調用你的'子類'上的本地數組方法(例如拼接,縮小,移位),它就會失敗。 –