// Array Remove - By John Resig (MIT Licensed)Array.prototype.remove = function(from, to) {var rest = this.slice((to || from) + 1 || this.length);this.length = from < 0 ? this.length + from : from;return this.push.apply(this, rest);};
下面是一些如何使用它的例子:
// Remove the second item from the arrayarray.remove(1);// Remove the second-to-last item from the arrayarray.remove(-2);// Remove the second and third items from the arrayarray.remove(1,2);// Remove the last and second-to-last items from the arrayarray.remove(-2,-1);
reindexArray : function( array ){var index = 0; // The index where the element should befor( var key in array ) // Iterate the array{if( parseInt( key ) !== index ) // If the element is out of sequence{array[index] = array[key]; // Move it to the correct, earlier position in the array++index; // Update the index}}
array.splice( index ); // Remove any remaining elements (These will be duplicates of earlier items)},
var arr = [{item: 1}, {item: 2}, {item: 3}];var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]var l = found.length;
while(l--) {var index = arr.indexOf(found[l])arr.splice(index, 1);}
console.log(arr.length); //1
不同:
var item2 = findUnique(2); //will return {item: 2}var l = arr.length;var found = false;while(!found && l--) {found = arr[l] === item2;}
console.log(l, arr[l]);// l is index, arr[l] is the item you look for
delete不是特定于数组的;它被设计用于对象:它从你使用它的对象中删除一个属性(键/值对)。它只适用于数组,因为JavaScript根本不是真正的数组*中的标准(例如,非类型)数组,它们是对某些属性具有特殊处理的对象,例如名称为“数组索引”(定义作为字符串名称“…其数值i在+0 ≤ i < 2^32-1”范围内”)和length的对象。当你使用delete删除数组条目时,它所做的只是删除该条目;它不会移动其他条目来填补空白,因此数组变得“稀疏”(一些条目完全缺失)。它对length没有影响。
let y = 1;let ary = [];console.log("Fatal Error Coming Soon");while (y < 4294967295){ary.push(y);ary[y] = undefined;y += 1;}console(ary.length);
它产生这个错误:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
因此,正如您所看到的,undefined实际上占用了堆内存。
但是,如果您还将ary项目delete(而不是将其设置为undefined),代码将慢慢完成:
let x = 1;let ary = [];console.log("This will take a while, but it will eventually finish successfully.");while (x < 4294967295){ary.push(x);ary[x] = undefined;delete ary[x];x += 1;}console.log(`Success, array-length: ${ary.length}.`);
var arr = [1, 2, 3 , 4, 5];
function del() {delete arr[3];console.log(arr);}del(arr);
在拼接原型中,参数如下。//arr.splice(开始删除的位置,要删除的项目数)
var arr = [1, 2, 3 , 4, 5];
function spl() {arr.splice(0, 2);// arr.splice(position to start the delete , no. of items to delete)console.log(arr);}spl(arr);