Detailed explanation of how to use the length attribute in jquery
In this article, we will explore some secrets of the length attribute in javascript through array like object. Example 1:
var obj={0:'a',1:'b'} alert(obj.length); //undefined var arr=['a','b'] alert(arr.length); // 2
From the above example, the length attribute in the array-like object is not directly linked to the amount of data it stores, whether it is the index attribute (0, 1) or The length attribute exists as a normal attribute of the object. There is no relationship between them. The js engine will not automatically calculate the length of the array-like object based on the amount of stored data.
But does the length of an array-like object really have nothing to do with the amount of data stored? Example 2 illustrates that this is not the case:Example 2:
function myarr(){} var m=new myarr(); Array.prototype.push.apply(m,['cson','lai','xiaoc']); alert(m.length);//IE8以下:undefined 其他浏览器:3 alert(m[2]);//IE8以下:undefined 其他浏览器:‘xiaoc'
As you can see from Example 2, except for versions below IE8, when adding elements to an array-like object by forcing the use of array methods, the length attribute of the object also will be calculated. It seems that versions below IE8 do not support forcing the use of array methods to add elements to array-like objects. Example 3:
This example adds an initialization operation in the myarr
constructor
of Example 2, adding an element when the array-like object is initialized, and something weird happens:
function myarr(){this[0]='cc';} var m=new myarr(); Array.prototype.push.apply(m,['cson','lai','xiaoc']); alert(m.length);//ie8以下:undefined 其他:3 alert(m[2]);//ie8以下:undefined 其他:xiaoc
Browsers of versions below ie8 continue to not support forced use of array methods. This will be discussed in the next example. For other browsers, the length attribute output is 3, and the element with index 2 is 'xiaoc'. Obviously the js engine completely ignores the element 'cc' with index 0 that originally existed in the array-like object! Let's look at the next example now. This example adds an additional initialization to the length attribute based on Example 3:
function myarr(){this[0]='cc'; this.length=1;}//多加一个length的初始化 var m=new myarr(); Array.prototype.push.apply(m,['cson','lai','xiaoc']); alert(m.length);//输出4 alert(m[2]);//输出'lai‘
Strange things happened again, this time all browsers (including ie6 7) output correctly 4. The element with index 2 is correctly output as 'lai'. It can be seen that after IE 6 and 7 added the initialization of the length attribute, the array method can be used normally.
Now try to initialize the length attribute to an illegal type:Example 4:
function myarr(){this[0]='cc'; this.length="bo";}//length设置为不能转换为number的不合法类型 var m=new myarr(); Array.prototype.push.apply(m,['cson','lai','xiaoc']); alert(m.length);//输出 3 alert(m[2]);// 输出'xiaoc‘
function myarr(){this[0]='cc'; this.length="1";}//length设置为能转换为数字的不合法类型 Array.prototype.push.apply(m,['cson','lai','xiaoc']); alert(m.length);//输出4 alert(m[2]);//输出'lai‘
From all the above examples, we can make an inference that when using the array method (here Taking push as an example), the process is roughly like this: IE6 7:
It can be seen that IE6 7 does not force the use of array methods to add elements, but it will first determine whether the length attribute exists, and if it does not exist, it will return. No action is taken. If the length attribute is an illegal value, try to convert it to the number type. If the conversion fails, the length is set to 0. This can parse the undefined output in Examples 2 and 3 and the correct output in Example 4.
Other browsers:
Other browsers will perform different operations based on the length attribute. If the length attribute does not exist, set the length to 0. If the length attribute is an illegal value, try to convert it to the number type. , if the conversion fails, length is also set to 0.
Because the length attribute plays such a decisive role in the array method, the js engine prohibits writing illegal values to the length attribute:
var arr=['1','2','3']; arr.length='undefined';//报错invalid array length
From the above example, we can conclude A conclusion: When we use array-like objects, in order to avoid weird problems caused by various incorrect length calculations, we should initialize the value of the length attribute when initializing the array-like object. If elements are added during initialization but length is not set, The value of the attribute. When using the array method, IE6 7 will ignore all operations, and other browsers will ignore elements added during initialization.
In addition, another problem caused by the length attribute:
Please see Example 5:
function myarr(){} myarr.prototype=new Array(); var m=new myarr(); m.push('cson','lai','xiaoc'); alert(m.length);//IE6 7:0 其他:3 alert(m[2]);//所有浏览器:'xiaoc‘
When using the prototype to inherit the
array, IE 6 7 length will always be 0, no matter how many elements you have, other browsers will be fine. Even if the length attribute is forcibly set, it will always be 0 under IE6 7:
function myarr(){} myarr.prototype=new Array(); var m=new myarr(); m.length=10; alert(m.length);//IE6 7:0 其他:10
Therefore, we can conclude that when the object prototype inherits an array under IE6 7, the length attribute will always be 0, so if the array-like object needs to use For array methods, do not inherit the array, but use the Array.prototype.xxx.apply(obj,[]); method, and remember to correctly initialize the value of the length attribute.
Get the length of
Object objectAll JS programmers (even more than JS) know that arrays (Array) have length, and through the length attribute, you can easily Conveniently obtains the length of an array. It can be said that as long as an array is used, its length attribute will be used.
The Object object does not have a length property or method. There is really no need for it to exist, because people will only care about what methods the object can provide, but there is no need to know how many methods it has. Indeed, this is indeed not a universal requirement, so ECMAScript will not add extra burden to itself.
I have never considered this issue before. We obtain data through CGI. For data one by one, the background makes it into an array and returns it as json. As follows:
try{callback({ data:[{a:1},{a:2}] }); }catch(e){}
这是非常合理的,因为我在前端可以用length得到数据的长度,并逐条将其插入表格,或者是通过其他的方式表现出来。但是你永远也不能用一成不变的思维方式来解决所有问题。
某天写后台接口的同事决定换一种数据格式,改用object来表示数据,并为每个数据添加一个索引,如下所示:
try{callback({ data:{1:{a:1},2:{a:2}} }); }catch(e){}
面对这样的数据,我就犯愁了,因为object不能获取对象长度。当然我可以叫后台同事改一下接口返回的格式,但是既然他可以写出以这样格式返回的代码,那其他的后台同事也同样
可以写出。为了不影响到更多的人,就需要我在前端来做处理了。其实要获取对象的长度也不难,用for in 语句就能实现,如下代码所示:
var a = {a:1,b:2,c:3,d:4}; function length(o) { var count = 0; for(var i in o){ count ++; } return count; }; alert(length(a)); //5
至于为什么是5而不是4那是因为每个对象都有一个内部属性(proto指向原型)。
为了更方便的使用这个方法,可以把它写到Object原型里面去,如下代码所示:
var a = {a:1,b:2,c:3,d:4}; Object.prototype.length = function() { var count = 0; for(var i in this){ count ++; } return count; }; alert(a.length()); //5
这样用起来会更直观,跟接近Array的使用习惯。
The above is the detailed content of Detailed explanation of how to use the length attribute in jquery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Many friends still don’t know how to use Baidu Netdisk, so the editor will explain how to use Baidu Netdisk below. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: Log in directly after installing Baidu Netdisk (as shown in the picture); Step 2: Then select "My Sharing" and "Transfer List" according to the page prompts (as shown in the picture); Step 3: In "Friend Sharing", you can share pictures and files directly with friends (as shown in the picture); Step 4: Then select "Share" and then select computer files or network disk files (as shown in the picture); Fifth Step 1: Then you can find friends (as shown in the picture); Step 6: You can also find the functions you need in the "Function Treasure Box" (as shown in the picture). The above is the editor’s opinion

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work

Potplayer is a very powerful media player, but many friends still don’t know how to use potplayer. Today I will introduce how to use potplayer in detail, hoping to help everyone. 1. PotPlayer shortcut keys. The default common shortcut keys for PotPlayer player are as follows: (1) Play/pause: space (2) Volume: mouse wheel, up and down arrow keys (3) forward/backward: left and right arrow keys (4) bookmark: P- Add bookmarks, H-view bookmarks (5) full screen/restore: Enter (6) multiple speeds: C-accelerate, 7) Previous/next frame: D/

I believe that many users are using the Xiaoma win7 activation tool, but do you know how to use the Xiaoma win7 activation tool? Then, the editor will bring you how to use the Xiaoma win7 activation tool. For those who are interested in this, please come to the following article Let's see. The first step is to go to "My Computer" after reinstalling the system, click "System Properties" in the upper menu, and check the Windows activation status. In the second step, click to download the win7 activation tool online and click to open it (there are many resources available everywhere). The third step is to open the Xiaoma activation tool and click "Activate Windows permanently". The fourth step is to wait for the activation process to complete activation. Step 5: Check the Windows activation status again and find that the system has been activated.

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus
