简体   繁体   English

获取对象内部数组的长度

[英]Getting the length of an array inside an object

I have a JavaScript object which includes an array. 我有一个包含数组的JavaScript对象。 I created a new key, length , which is supposed to store the value of the length of the fields array. 我创建了一个新的键length ,它应该存储fields数组的length值。

$(document).ready(function() {
var data = {
    "label": "Information",
    "fields": [
        {
            "name": "name",
            "label": "Team Name",
            "type": "string",
            "config": {}
        }
    ],
    "length": fields.length     // Need help with this line
};
$("button").click(function() {
    alert(data.length);
});
});

http://jsfiddle.net/kvtywmtm/ http://jsfiddle.net/kvtywmtm/

In my fiddle, nothing gets alerted, although it should alert 1, since there is 1 record in the fields array. 在我的小提琴中,没有任何警报,尽管它应该警报1,因为在fields数组中有1条记录。

Any ideas? 有任何想法吗?

Edit 编辑

I know you can get the length OUTSIDE of the object by creating a new variable 我知道您可以通过创建新变量来获得对象的外边长度

var length = data.fields.length;

However, I need the length to be inside of the object. 但是,我需要长度在对象内部。

You can use a getter 您可以使用吸气剂

 $(document).ready(function() { var data = { "label": "Information", "fields": [{ "name": "name", "label": "Team Name", "type": "string", "config": {} }], get length() { return this.fields.length } }; $("button").click(function() { console.log(data.length); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <button>Click Here</button> 

var data = {
    "label": "Information",
    "fields": [
        {
            "name": "name",
            "label": "Team Name",
            "type": "string",
            "config": {}
        }
    ],
};
data.length = fields.length;

This won't auto-update the length field, but it doesn't seem as if you need it to. 这不会自动更新length字段,但似乎并不需要。

Try this JSFiddle 试试这个JSFiddle

I don't know what length you need in the alert, but if you need the object data properties length you need the following. 我不知道警报中需要多少长度,但是如果您需要对象data属性的长度,则需要以下内容。 Also, to pass fields length you need to add it after declare the array: 另外,要传递fields长度,您需要在声明数组之后添加它:

JS: JS:

$(document).ready(function() {
    var data = {
        "label": "Information",
        "fields": [
            {
                "name": "name",
                "label": "Team Name",
                "type": "string",
                "config": {}
            }
        ]
    };

    data.length = data.fields.length

    $("button").click(function() {
        alert(Object.keys(data).length);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM