console.time("shift") let arr1 = new Array(100000).fill(1); while(arr1.length) { arr1.shift(); } console.timeEnd("shift"); // shift: 845.883056640625 ms
时间复杂度:O(n²),每次都要移动剩余的所有元素,从数组开头移除一个元素时,需要将数组中剩下的所有元素都向前移动一位,以填补被移除元素的位置 对于一个长度为 n 的数组,第一次 shift()需要移动 n-1 个元素,第二次 shift()需要移动 n-2 个元素…
pop
1 2 3 4 5 6 7
console.time("pop") let arr1 = new Array(100000).fill(1); while(arr1.length) { arr1.pop(); } console.timeEnd("pop"); // pop: 2.234130859375 ms 时间复杂度:O(n),需要执行n次pop操作
splice
1 2 3 4
console.time("splice") let arr1 = new Array(100000).fill(1); arr1.splice(0,arr1.length); console.timeEnd("splice"); // splice: 1.026123046875 ms
从索引 0 开始,移除数组中所有元素
arr.leng = 0(最优方案)
1 2 3 4
console.time("length0") let arr1 = new Array(100000).fill(1); arr1.length = 0; console.timeEnd("length0"); // length0: 0.72998046875 ms