[英]“'length' in Object(obj)” How does it work in js?
'length' in Object(obj)
How does the above statement works in JavaScript? 上面的语句如何在JavaScript中起作用?
I have found the below JavaScript statement in angular.js lib 我在angular.js lib中找到了以下JavaScript语句
var length = 'length' in Object(obj) && obj.length;
Object(...)
converts primitives to object structure. Object(...)
将基元转换为对象结构。 Examples: 例子:
Object(null) // {}
Object(undefined) // {}
Object(10) // Number {[[PrimitiveValue]]: 10}
If you type 'length' in 10
it will throw an error, but 'length' in Object(10)
will not (returns false and blocks next statement, which would throw an error if obj
has a primitive value). 如果'length' in 10
键入'length' in 10
则将引发错误,但是'length' in Object(10)
将不会(返回false并阻止下一条语句,如果obj
具有原始值,则将引发错误)。
Your code checks if obj
variable is an array or array-like object (has length property). 您的代码检查obj
变量是数组还是类似数组的对象(具有length属性)。
More about Object and in operator . 有关对象和in运算符的更多信息。
That will check whether the property length
exists in Object(obj)
or not 这将检查属性length
是否存在于Object(obj)
I guess that is to differentiate between Array and Object. 我想这是要区分数组和对象。
Because Object doesn't have the property length
so it will false for Object. 因为Object没有属性length
所以对于Object它将为false。
var a = { name: "abc", age: "34" }; var l = 'length' in Object(a) && a.length; console.log(l);
But array have the property length
and it will return the length of the array. 但是array具有length
属性,它将返回数组的长度。
var b = [34, 54, 65]; var ll = 'length' in Object(b) && b.length; console.log(ll);
When we type checking them, both are same. 当我们键入检查它们时,两者是相同的。
var a = []; var b = {}; console.log(typeof a, typeof b);
There are other methods to differentiate Array and Object too. 还有其他区分数组和对象的方法。
Using Array.isArray
使用Array.isArray
var a = []; var b = {}; console.log(Array.isArray(a)); console.log(Array.isArray(b));
var length = Object.keys(myArray).length;
Or 要么
Universal function:- 通用功能:-
var objSize = function(obj) { var count = 0; if (typeof obj == "object") { if (Object.keys) { count = Object.keys(obj).length; } else if (window._) { count = _.keys(obj).length; } else if (window.$) { count = $.map(obj, function() { return 1; }).length; } else { for (var key in obj) if (obj.hasOwnProperty(key)) count++; } } return count; }; document.write(objSize({ a: 1, b: 2, c: 3 }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.