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
,因爲點是公司將值在兩個不同的數組中循環。
如果通過「操作次數」,你的意思是它的「大O」行爲,當然它不是O(1);至少O(n)很可能更糟糕。除了它的性能(可能不那麼好),還有其他一些不使用'join'的原因。例如,你的'join'方法會報告'['a&b','c']'等於'['a','b&c']'。除了循環訪問陣列之外,還有其他更快的選擇是不太可能的。只是我們的好奇心,從哪裏開始關注效率呢? – 2015-11-01 11:38:18
加入可能是「最便宜」,但絕對是最差的,因爲它根本無法正常工作。示例:'[1,2,3] .join('&&')=== ['1',2,3] .join('&&')// true'雖然'「1」=== 1// => false'。甚至沒有提到你將無法比較非基元數組。 – dfsq
a [i] === b [i]在方法A中會比較不是數組項,它會比較內存中的指針。使用== – ivan