Javascript 从阵列原型内部移除元素
我试图在angular service中扩展js本机数组,以添加一些额外的特性,而无需原型化全局对象Javascript 从阵列原型内部移除元素,javascript,arrays,angularjs,prototype-pattern,Javascript,Arrays,Angularjs,Prototype Pattern,我试图在angular service中扩展js本机数组,以添加一些额外的特性,而无需原型化全局对象 app.factory('Collection', function($http, $q) { var Collection = function(arr) { this.key = 'id'; this._last = 0; this._first = 77777777; //just big number. this.a
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
});
但是,在调用StipleBy:*(如果一行中有两个元素要删除,则
StipleBy
函数将不起作用,因为splice正在将索引从i更新为array.length。请尝试以下操作:
Collection.prototype.spliceBy = function(key, val) {
var i = this.length;
while (i--) {
if (this[i][key] !== val) {
this.splice(i, 1); ///THIS NEVER HAPPENS !!
console.log('removed ' + i + ' from ', this);
}
}
}
这看起来不对
Collection.prototype=new Array;
。在ES5中不能这样做。但可以在ES6中对数组进行子类化。@Elclans对此不确定,但在我的所有浏览器和cordova应用程序中都可以正常工作:-)如果正常工作,为什么要发布此问题?数组不是子类,除了最新版本的Chrome/Edge(还没有FF),甚至需要使用(本机)类语法。使其工作的唯一(我的意思是唯一)其他方法是编写一个包含内部数组实例的包装器类,它根据需要委托给该实例,或者委托给monkey patch array.prototype。一旦你试图在你的“子类”上调用一个本机数组方法(如splice、reduce、shift),它就会失败。我知道,因为我也尝试过用Maps做同样的事情
Collection.prototype.spliceBy = function(key, val) {
var i = this.length;
while (i--) {
if (this[i][key] !== val) {
this.splice(i, 1); ///THIS NEVER HAPPENS !!
console.log('removed ' + i + ' from ', this);
}
}
}