sort方法用來對數組元素進行排序。可是瀏覽器實現可能有不一樣,已經兩次踩到坑了,所以記錄一下。chrome
ecma-262制定的排序規則:
使用兩個參數x和y喚起排序數組
一、若是x、y都是undefined,返回 +0
二、若是x爲undefined,返回 1
三、若是y未undefined,返回 -1
四、若是定義了排序方法瀏覽器a、設v = ToNumber(comparefn(x, y)) b、若是v是NaN,返回 +0 c、返回v五、設xString = ToString(x)
六、設yString = ToString(y)
七、若是xString < yString,返回 -1
八、若是yString < xString,返回 1
九、返回 +0
當返回1的時候,x應排在y後面
返回0的時候,x、y位置不變
返回-1的時候,x應排在y前面函數
坑1:排序不必定是穩定的,即相等的兩個元素不必定會保持在原來的位置。排序方法返回0的兩個元素仍可能交換位置,如chrome瀏覽器的排序實現,在數組長度小於等於10的時候就使用插入排序法,沒有什麼問題,可是數組大於10的時候就會使用快速排序,在比較起始值和中值的時候,排序方法返回值大於和等於0的時候都會對調位置。
我遇到的狀況是,須要對會員卡數組進行兩個維度的比較排序,數組元素對象可能包含次卡或者折扣屬性,次卡排在折扣卡前面,折扣卡按折扣大小排序。當時我寫的排序方法爲:(a, b) => { return (a.discount && b.times) || a.discount > b.discount },後來發現有時次卡沒有排在折扣卡前面,改成:(a, b) => { if ((a.discount && b.times) || a.discount > b.discount) return 1; return -1; })測試
坑2:如上面排序規則第4條a,按標準須要把排序方法返回值轉爲Number類型,可是有些瀏覽器版本如Safari10並無實現這一步,若是排序方法返回true/false布爾值而不是Number類型,元素位置就不會進行調整。code
every方法測試一個數組內的全部元素是否都能經過某個指定函數的測試。結果會返回一個布爾值,直覺認爲空數組會返回false對象
callbackfn should be a function that accepts three arguments and
returns a value that is coercible to the Boolean value true or false.
every calls callbackfn once for each element present in the array, in
ascending order, until it finds one where callbackfn returns false. If
such an element is found, every immediately returns false. Otherwise,
if callbackfn returned true for all elements, every will return true.
callbackfn is called only for elements of the array which actually
exist; it is not called for missing elements of the array
如規範解釋,every方法對數組中的每個元素(排除空元素)經過指定的函數進行檢測,當有某一個元素檢測爲false的時候,every方法馬上返回false,也只有這種狀況會返回false,那麼空數組就會返回true!排序