Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取JSON对象中的键数?_Javascript_Jquery_Json - Fatal编程技术网

Javascript 如何获取JSON对象中的键数?

Javascript 如何获取JSON对象中的键数?,javascript,jquery,json,Javascript,Jquery,Json,我正在创建一个gallery插件,在这个插件中,我需要计算出一个普通javascript对象中元素的数量。以下是我希望能够创建图库的方式 $.Gallery.create($('#galContainer'), { 'img1.png': 'http://linktosomewhere/', 'img2.png': 'http://linktosomewhere/', 'img3.png': 'http://linktosomewhere/', ........

我正在创建一个gallery插件,在这个插件中,我需要计算出一个普通javascript对象中元素的数量。以下是我希望能够创建图库的方式

$.Gallery.create($('#galContainer'), {
    'img1.png': 'http://linktosomewhere/',
    'img2.png': 'http://linktosomewhere/',
    'img3.png': 'http://linktosomewhere/',
    ........
}, optionsObj);
这将在单击时将图像与指向某个页面的相应链接一起放入图库。目前,我正在为第二个参数使用一个数组,没有链接,我正在使用images.length获取图像的长度。然而,使用上面的符号对我来说是理想的,我需要能够知道这个对象中有多少个键


我知道还有一些人说你不能得到对象中元素的数量。如果确实是这样,您对设置此函数调用的另一种方法有什么建议吗?这种方法既高效又易于使用?

您在链接的另一个问题中看到的代码实际上是唯一的方法。以下是创建函数的方法:

function count(obj) {
  var i = 0;
  for (var x in obj)
    if (obj.hasOwnProperty(x))
      i++;
  return i;
}
就个人而言,我会为Object构建自己的原型,您可以使用
MyObject.length
,但我认为IE并不完全支持它

测试表明,长度变量在对象中不可用

测试用例:

MyObject = {
    a : '0',
    b : '1',
    c : '2'
}
if(MyObject.count() > 5)
{
    $.Gellery.Error('Images','Only 5 images allowed'); //...
}

您不能改用对象数组吗

$.Gallery.create($('#galContainer'), [
    {src:'img1.png', href:'http://linktosomewhere/'},
    {src:'img2.png', href:'http://linktosomewhere/'},
    {src:'img3.png', href:'http://linktosomewhere/'},
    ........
], optionsObj);
您只需在代码中添加
.src
.href
即可阅读


将数据集设计为简单散列的方式对于其他属性(大小、类别、所选对象等)不是很灵活。

underline.js有一种方法可以告诉您对象的大小(obj)

您还应该使用
var
声明
x
。当前版本使用global
x
。感谢casa,我一定会将其添加到我的函数库中,稍后再使用。但是我认为对于这个特定的实例,我不希望依赖于此。您还应该使用
var
声明
I
c
。当前版本使用全局
i
c
。好主意!谢谢你的帮助!
$.Gallery.create($('#galContainer'), [
    {src:'img1.png', href:'http://linktosomewhere/'},
    {src:'img2.png', href:'http://linktosomewhere/'},
    {src:'img3.png', href:'http://linktosomewhere/'},
    ........
], optionsObj);