Longueur d'un objet JavaScript

Mots clés : javascriptjavascript-objectsjavascript

meilleur 5 Réponses Longueur d'un objet JavaScript

vote vote

90

var size = Object.keys(myObj).length; 
var person = {   [Symbol('name')]: 'John Doe',   [Symbol('age')]: 33,   "occupation": "Programmer" };  const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1  let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2
Object.size = function(obj) {   var size = 0,     key;   for (key in obj) {     if (obj.hasOwnProperty(key)) size++;   }   return size; };  // Get the size of an object const myObj = {} var size = Object.size(myObj);
vote vote

89

Object.keys(myArray).length 
vote vote

77

_.size({one : 1, two : 2, three : 3}); => 3 
$.assocArraySize = function(obj) {     // http://stackoverflow.com/a/6700/11236     var size = 0, key;     for (key in obj) {         if (obj.hasOwnProperty(key)) size++;     }     return size; }; 
vote vote

68

if (!Object.keys) {     Object.keys = function (obj) {         var arr = [],             key;         for (key in obj) {             if (obj.hasOwnProperty(key)) {                 arr.push(key);             }         }         return arr;     }; }  Object.keys(obj).length; 
vote vote

60

var element_count = 0; for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; } 

Questions similaires