Javascript中length属性的总结
一、StringObject中的length
length属性是返回字符串的字符数目。
例如:
// 普通字符串
var str = "abcdef";
console.log(str.length); //
// 数组
var str1 = new Array(1,2,3,4);
console.log(str1.length); //
// 数组与字符串
var str2 = str1 + str; // "abcdef1,2,3,4"
console.log(str2.length); //
// 对象和对象
var obj = {};
console.log(obj.length); // undefined
var obj += obj; // "[object Object][object Object]"
console.log(obj.length); //
二、Function中的length
length可以返回function的参数数目。
var a = function(a,b,c,d){};
console.log(a.length); //
var b = RegExp;
console.log(b.length); //new RegExp(pattern, attributes)构造方法中有两个参数, 所以length为2
※ arguments实例的length属性则是返回调用程序传递给函数的实际参数数目。
var a = function(){
console.log(arguments.length);
};
a(1,2,3); //
a(); //
注: 众所周知,在javascript中没有方法的重载,而arguments实例恰好可以帮我们来模拟方法的重载。