Home  >  Article  >  Web Front-end  >  Should I use size or length for array length?

Should I use size or length for array length?

青灯夜游
青灯夜游Original
2021-04-27 13:50:1110309browse

The length of the array uses the length attribute. Length is a native method of js, which can obtain the number of elements and the length of the object; and the size() function is a jQuery method that can only be used on objects and is used to return the number of elements encapsulated by the current jQuery object. To get the length of an array or the length of a parameter, you can only use lenth.

Should I use size or length for array length?

The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.

The difference between length and size

I have used length for a long time and have never considered the difference between length and size. Today my colleague asked about it and I searched for information specifically. List the similarities and similarities between the two.

Similar points: used to return the number of elements in jQuery, the size() function has the same effect as the length attribute. The return value of the size() method is consistent with the length property of the jQuery object.

Grammar

$("selector").size()
$("selector").length

Example code

<div>
 <ul>
    <li>后台专区</li>
    <li>前台专区</li>
    <li>数据库专区</li>
    <li>站长交流</li>
  </ul>
</div>
$("li").size==$("li").length      //4

Difference:

The first thing to note is that the usage of size is size(), and the size() function is the jQuery method. It belongs to the jQuery object (instance) and is used to return the number of elements encapsulated by the current jQuery object. It cannot be used in native js. length is a native js method (property).

To get the length of a string, you can only use length, such as $("#text").val().length. You cannot use size

to get the length of an array or the length of a parameter. You can only use lenth, such as arry.length, but not size.

As can be seen from the above, size() is implemented by calling the length attribute, and length replaced size() after jquery 1.8, because length No need to return a function call, which is better.

Recommended tutorial: jQuery tutorial

The above is the detailed content of Should I use size or length for array length?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn