如何获取对象的数量(数据)

时间:2022-07-23 16:53:21

My Code:

$.post("@(Url.Action("SelectAction", "ControllerName"))", function(data){
    // How to get the count of the data(object)
});

How to get the count of the data(object). I used data.count but is returning as "undefined".

如何获取数据(对象)的计数。我使用了data.count但是返回为“undefined”。

2 个解决方案

#1


0  

If you want to count the no. of properties in an object, you could use:

如果你想数不。对象中的属性,您可以使用:

Object.keys(data).length

Or if you want a cross-browser approach, you'll need to loop through the object itself using:

或者,如果您需要跨浏览器方法,则需要使用以下方法遍历对象本身:

var count = 0;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        count++;
    }
}

#2


0  

Use Object.keys as pointed out in other answers (Object.keys(data).length).

使用其他答案中指出的Object.keys(Object.keys(data).length)。

Don't use a temporary fix if you want cross-browser compatibility however. Use a shim. It's simple enough and will just be better for newer browsers. Old browsers will simply use the shim.

如果您想要跨浏览器兼容性,请不要使用临时修复。使用垫片。这很简单,对于较新的浏览器会更好。旧浏览器将简单地使用垫片。

Quick shim:

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

Source: http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html

#1


0  

If you want to count the no. of properties in an object, you could use:

如果你想数不。对象中的属性,您可以使用:

Object.keys(data).length

Or if you want a cross-browser approach, you'll need to loop through the object itself using:

或者,如果您需要跨浏览器方法,则需要使用以下方法遍历对象本身:

var count = 0;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        count++;
    }
}

#2


0  

Use Object.keys as pointed out in other answers (Object.keys(data).length).

使用其他答案中指出的Object.keys(Object.keys(data).length)。

Don't use a temporary fix if you want cross-browser compatibility however. Use a shim. It's simple enough and will just be better for newer browsers. Old browsers will simply use the shim.

如果您想要跨浏览器兼容性,请不要使用临时修复。使用垫片。这很简单,对于较新的浏览器会更好。旧浏览器将简单地使用垫片。

Quick shim:

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

Source: http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html