jQuery length和size()區別總結如下: 1.length是屬性,size()是方法。 2.如果你只是想獲取元素的個數,兩者效果一樣既 $("img").length 和 $("img").size() 獲取的值是一樣的。 3.如果計算一個字元串的長度或者計算一個數組元素的個數就只得用 ...
jQuery length和size()區別總結如下:
1.length是屬性,size()是方法。
2.如果你只是想獲取元素的個數,兩者效果一樣既 $("img").length 和 $("img").size() 獲取的值是一樣的。
3.如果計算一個字元串的長度或者計算一個數組元素的個數就只得用length, 如 $("#text").val().length。
看看他們的執行時間,http://jsperf.com/size-vs-length用這個檢測的
從圖中可以看到size()方法比length慢38%,原因何在?
原因在此:
看看官網的解釋(http://api.jquery.com/size/):
The .size()
method is deprecated as of jQuery 1.8. Use the
.length
property instead.
The .size()
method is functionally equivalent to the .length
property; however,
the .length
property is preferred because it does not have the overhead of a function call.
從上可以看出size()是調用length屬性實現的
在jquery 1.8後 length取代了 size() ,因為length不需要返回一個函數調用,更優秀。