javascript数组的remove⽅法
javascript原⽣⼀直没有提供删除功能,于是⾃⼰写了⼏个remove⽅法,主要是要注意遍历数组时使⽤splice⽅法是会在遍历没完成时就会改变数组对象的length长度,最简单⽅法是从数组尾部开始遍历,⽤递减来循环,就像我这⾥LastRmove的注释部分,这种⽅法直观⼜不受长度动态变化 的影响,然后我想是不是也要像undescore⼀样加上前后顺序和匹配到第⼀个就返回这种功能,于是就作了些⼩改动,可以从头部或是尾部匹配第⼀个移除后就返回,或是遍历整个数组。
// 遍历整个数组,移除匹配item的元素,使⽤强⽐较===,给第⼆个参数的话就从头开始找到第⼀个匹配item元素移除后返回;// 如有找到元素返回处理后的数组⾃⾝,如果没有找到过就返回undefined;Array.prototype.Remove = function (item, all) {
var result, isType = Object.prototype.toString, i, len, start, hasLast = arguments[2]; start = 0, len = this.length; for (i = start; i < len;) { var isPass = true, inx; if (!hasLast) { inx = i; } else {
inx = len - 1; }
if (isType.call(item) == '[object Array]') {
for (var ii = 0, iimax = item.length; ii < iimax; ii++) { if (this[inx] === item[ii]) { isPass = false; break; } }
} else if (this[inx] === item) { isPass = false; }
if (!isPass) { result = true;
this.splice(inx, 1); if (all) { break; }
} else if (!hasLast) { len = this.length; i++; } else { len--; } }
return result ? this : void 0;}
// 同上⾯的Rmove,从尾部开始查找,找到后删除第⼀个匹配的⽴刻返回;// 如有找到元素返回处理后的数组⾃⾝,如果没有找到过就返回undefined;Array.prototype.LastRemove = function (item) {
/* var result = [], isType = Object.prototype.toString.call,isFrist; for (var i = this.length - 1; i >= 0; i--) { var isPass = true;
if (Object.prototype.toString.call(item) == '[object Array]') { for (var ii = 0, iimax = item.length; ii < iimax; ii++) { if (this[i] === item[ii]) { isPass = false; break; } }
} else if (this[i] === item) { isPass = false; }
if (!isPass) {
if(isFrist && !all){ break ; }
isFrist = true; this.splice(i, 1); } }*/
return this.Remove(item, true, true);}
// 效果同上⾯的,遍历整个数组,区别是于 返回的是个新的数组,是原数组的引⽤;Array.prototype.RemoveAt = function (item) {
var result = [], isType = Object.prototype.toString, isPass, val; for (var inx = 0, len = this.length; inx < len; inx++) { isPass = true; val = this[inx];
if (isType.call(item) == '[object Array]') {
for (var ii = 0, iimax = item.length; ii < iimax; ii++) { if (val === item[ii]) { isPass = false; break;
} }
} else if (val === item) { isPass = false; }
if (isPass) {
result.push(val); } }
return result; }