2015-11-01 40 views
0

Javascript Array Join方法有多少操作?Javascript Array Join操作中有多少個操作?

它只是一個操作,還是操作次數與數組中的項數相同?

我之所以這樣問是因爲我想知道的是下面的兩個數組比較便宜的方式:

var a = ["Apples", "Pears", "Bananas"] 
var b = ["Apples", "Oranges", "Bananas"] 

方法A

For (var i = 0; i < 2; i++) { 
    if (a[i] === b[i]) console.log(false); 
} 

方法B

aa = a.join("&"); 
bb = b.join("&"); 
if (aa === bb) console.log(false) 

最便宜的方式,不寫只a === b,因爲點是公司將值在兩個不同的數組中循環。

+3

如果通過「操作次數」,你的意思是它的「大O」行爲,當然它不是O(1);至少O(n)很可能更糟糕。除了它的性能(可能不那麼好),還有其他一些不使用'join'的原因。例如,你的'join'方法會報告'['a&b','c']'等於'['a','b&c']'。除了循環訪問陣列之外,還有其他更快的選擇是不太可能的。只是我們的好奇心,從哪裏開始關注效率呢? – 2015-11-01 11:38:18

+2

加入可能是「最便宜」,但絕對是最差的,因爲它根本無法正常工作。示例:'[1,2,3] .join('&&')=== ['1',2,3] .join('&&')// true'雖然'「1」=== 1// => false'。甚至沒有提到你將無法比較非基元數組。 – dfsq

+1

a [i] === b [i]在方法A中會比較不是數組項,它會比較內存中的指針。使用== – ivan

回答

4

的所述ECMAScript 2015 (6th Edition, ECMA-262)Array.prototype.join (separator)執行以下步驟:

Let O be ToObject(this value). 
ReturnIfAbrupt(O). 
Let len be ToLength(Get(O, "length")). 
ReturnIfAbrupt(len). 
If separator is undefined, let separator be the single-element String ",". 
Let sep be ToString(separator). 
ReturnIfAbrupt(sep). 
If len is zero, return the empty String. 
Let element0 be Get(O, "0"). 
If element0 is undefined or null, let R be the empty String; otherwise, let R be ToString(element0). 
ReturnIfAbrupt(R). 
Let k be 1. 
Repeat, while k < len 
    Let S be the String value produced by concatenating R and sep. 
    Let element be Get(O, ToString(k)). 
    If element is undefined or null, let next be the empty String; otherwise, let next be ToString(element). 
    ReturnIfAbrupt(next). 
    Let R be a String value produced by concatenating S and next. 
    Increase k by 1. 
Return R. 

注:

  • 數組的元素轉換爲字符串,然後將這些字符串被串接,按出現分離的分離器。如果未提供分隔符,則使用單個逗號作爲分隔符。
  • 連接函數是有意通用的;它不要求它的這個值是一個Array對象。因此,它可以轉移到其他類型的對象以用作方法。

我會說你的第一種方法更便宜:)但你可以運行你自己的基準。

1

根據定義,幾乎沒有什麼比以下更快,假設你想做一個淺層比較。

function equal(a, b) { 
    if (a === b) return true; 
    if (a.length !== b.length) return false; 
    for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; 
    return true; 
} 

quick test表明,這是比使用joinstringify或快50倍。

+0

感謝您編寫測試 – Dol