jQuery length 和 size

2019-12-30  本文已影响0人  叩丁狼教育

本文为叩丁狼高级讲师原创文章,转载请注明出处。

总是有些时候,会发现一些属性或者方法在存在一些相同或者相似相近的东西,比如最近看到到的jquery中的length和size。两个都表示jquery中对象元素的个数。

首先最明显的区别:

length是属性,size()是方法

如果只是想获取元素的个数,两者的结果数据是一样的。

比如

HTML 代码: <img src="test1.jpg"/>

<img src="test2.jpg"/>

jQuery 代码: $("img").length; //结果:2

HTML 代码: <img src="test1.jpg"/>

<img src="test2.jpg"/>

jQuery 代码: $("img").size(); //结果:2

只不过,从1开始计算数组长度

但是如果是获取字符串的长度就只得用length, 比如:

HTML 代码: <p id="text">你是我的小丫小苹果</p>

jQuery 代码: $("#text").val().length

执行效率方面:

图片1.png

通过这个链接可以查看到两者的执行情况:<u>https://jsperf.com/size-vs-length</u>

通过以上的链接测试结果来看,length的效率显然要高于size方法。

<u>http://api.jquery.com/size/</u>

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 preferredbecause it does not have the overhead of a function call.

Given a simple unordered list on the page:

<ul>

<li>foo</li>

<li>bar</li>

</ul>

Both .size() and .length identify the number of items:

alert( "Size: "+ $( "li" ).size() );

alert( "Size: "+ $( "li" ).length );

This results in two alerts:

Size: 2

Size: 2

Example:

Count the divs. Click to add more.

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>size demo</title>

<style>

body {

cursor: pointer;

min-height: 100px;

}

div {

width: 50px;

height: 30px;

margin: 5px;

float: left;

background: blue;

}

span {

color: red;

}

</style>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>

<body>

<span></span>

<div></div>

<script>

$( document.body )

.click(function() {

$( this ).append( $( "<div>" ) );

var n = $( "div" ).size();

$( "span" ).text( "There are " + n + " divs. Click to add more." );

})

// Trigger the click to start

.click();

</script>

</body>

</html>

可以看出来,size()是调用length属性实现的。在jquery 1.8后 length取代了 size() ,因为length不需要返回一个函数调用,更优秀。

上一篇 下一篇

猜你喜欢

热点阅读