如何计算JavaScript数组对象? [英] How to count JavaScript array objects?

查看:168
本文介绍了如何计算JavaScript数组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有这样的JavaScript数组时:

When I have a JavaScript array like this:

var member = {
    "mother": {
        "name" : "Mary",
        "age" : "48"
    },
    "father": {
        "name" : "Bill",
        "age" : "50"
    },
    "brother": {
        "name" : "Alex",
        "age" : "28"
    }
}

如何计算此数组中的对象?!
我的意思是如何得到一个计数结果3,因为里面只有3个物体:母亲,父亲,兄弟?!

How to count objects in this array?!
I mean how to get a counting result 3, because there're only 3 objects inside: mother, father, brother?!

如果它不是数组,那么如何将其转换为JSON数组?

推荐答案

这不是数组,是一个对象文字,你应该迭代对象的自己的属性并计算它们,例如:

That's not an array, is an object literal, you should iterate over the own properties of the object and count them, e.g.:

function objectLength(obj) {
  var result = 0;
  for(var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
    // or Object.prototype.hasOwnProperty.call(obj, prop)
      result++;
    }
  }
  return result;
}

objectLength(member); // for your example, 3

hasOwnProperty 方法应该用于避免迭代继承的属性,例如

The hasOwnProperty method should be used to avoid iterating over inherited properties, e.g.

var obj = {};
typeof obj.toString; // "function"
obj.hasOwnProperty('toString'); // false, since it's inherited

这篇关于如何计算JavaScript数组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆