Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to use the length attribute in jquery

伊谢尔伦
Release: 2017-06-17 13:16:28
Original
3143 people have browsed it

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
Copy after login

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'
Copy after login

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
Copy after login

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‘
Copy after login

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‘
Copy after login
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‘
Copy after login

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
Copy after login

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‘
Copy after login

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
Copy after login

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 object

All 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){}
Copy after login

 这是非常合理的,因为我在前端可以用length得到数据的长度,并逐条将其插入表格,或者是通过其他的方式表现出来。但是你永远也不能用一成不变的思维方式来解决所有问题。

  某天写后台接口的同事决定换一种数据格式,改用object来表示数据,并为每个数据添加一个索引,如下所示:

try{callback({     
data:{1:{a:1},2:{a:2}}    
 });  
}catch(e){}
Copy after login

面对这样的数据,我就犯愁了,因为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
Copy after login

至于为什么是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
Copy after login

  这样用起来会更直观,跟接近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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!