简体   繁体   English

是否始终需要在整个链中(或依次)始终调用对象?

[英]Is it always required to call an object all the way through the chain (or in order)?

I'm trying to look through reddit's API. 我正在尝试浏览reddit的API。 I have seen a fiddle where they grab the image url from the site. 我看过一个小提琴 ,他们从网站上获取图像URL。 However, I'm confused as to how they are getting the objects themselves. 但是,我对它们如何获取对象本身感到困惑。 In their each() statement, they used data.data.children and item.data.url , however I cannot find a data object right after another data object in the json here http://www.reddit.com/r/pics.json . 在他们的each()语句中,他们使用了data.data.childrenitem.data.url ,但是我无法在json的另一个数据对象之后的http://www.reddit.com/r/pics.json找到数据对象http://www.reddit.com/r/pics.json I also do not see item.data.url . 我也没有看到item.data.url if I look from the very beginning (the two first objects are "kind" and "data"). 如果我从一开始就看(前两个对象是“种类”和“数据”)。 What does this mean? 这是什么意思?

Given the code in the fiddle: 鉴于小提琴中的代码:

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
    $.each(data.data.children, function(i,item){
        $("<img/>").attr("src", item.data.url).appendTo("#images");
    });
});

data and item are both function parameters, and their names have no relation to any named key within the JSON. dataitem都是函数参数,它们的名称与JSON中的任何命名键都没有关系。

The parameter data represents the entire JSON structure, but as it's just a parameter whose name is not significant I shall call it foo instead to disambiguate it from the contents of that structure, hence foo.data refers to the child element named data within the first level of the JSON. 参数data表示整个JSON结构,但由于它只是一个名称不重要的参数,因此我将其命名为foo以便将其与该结构的内容区foo.data来,因此foo.data 第一个foo.data引用了名为data的子元素。 JSON级别。

The item parameter represents each element in the array foo.data.children , so item.data.url for the first item would be equivalent to data.children[0].data.url within the JSON. item参数表示在阵列中的每个元件foo.data.children ,所以item.data.url的第一个项目将相当于data.children[0].data.url的JSON内。

The structure of the JSON returned is: 返回的JSON的结构为:

{
    data: {
        after: "",
        before: null,
        children: [
            {
                data: {
                    url: ""
                }
            },
            ...
        ],
        modhash: ""
    },
    kind: "Listing"
}

The name of the result variable is called data in the callback function parameters. 结果变量的名称在回调函数参数中称为data So to get to the children you need to type: 因此,要找到孩子,您需要输入:

data.data.children;

Next, in the $.each loop, each entry from the children array is assigned to an item variable in that callback function. 接下来,在$.each循环中, children数组中的每个条目都分配给该回调函数中的item变量。 It is from there where you drill down to the url . 从那里您可以深入到url property ( item.data.url ). 属性( item.data.url )。

You could name these whatever you want if data.data is confusing. 如果data.data令人困惑,则可以data.data命名。

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

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