使用JS這麼久, 對於JS數組的相關方法一直都是拿來就用,對於push
方法更是經常使用。可是在一次用到contact
方法的時候自問了一句: push
和contact
到底有哪些區別?chrome
先看下MDN的定義:數組
【push
】:adds one or more elements to the end of an array and
returns the new length of the array.
var animals = ['pigs', 'goats', 'sheep']; console.log(animals.push('cows')); // expected output: 4 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"] animals.push(['new arr']); // expected output: 5 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", Array(1)]
【contact
】:Theconcat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var array1 = ['a', 'b', 'c']; var array2 = ['d', 'e', 'f']; console.log(array1.concat(array2)); // expected output: Array ["a", "b", "c", "d", "e", "f"] console.log(array1); // expected output: Array ["a", "b", "c"] console.log(array2); // expected output: Array ["d", "e", "f"]
摘取重點:性能
push
方法添加元素到數組末尾,改變的是同一個數組, 返回值是添加以後數組的長度contact
方法是合併兩個或者多個數組,不會改變存在的數組,返回的是合併的數組那性能會不會有區別?code
環境:win8.1 chrome 63.0.3239.132ip
// push demo var arr3 = [1, 2, 3]; var arr4 = [4, 5, 6]; console.time('push'); for (let index = 10000; index > 0; index--) { arr3.push(...arr4); } console.timeEnd('push'); // push: 2.39892578125ms
// contact demo var arr1 = [1, 2, 3]; var arr2 = [4, 5, 6]; console.time('contact'); for (let index = 10000; index > 0; index--) { arr1 = arr1.concat(arr2); } console.timeEnd('contact'); // contact: 312.762939453125ms
在我這個環境上push+解構的性能是要好於contact的。不過對於多個數組合並的時候, contact由於返回的是新數組,能夠鏈式下去。element