JSON forEach() and function as a argument 解释

JSON forEach() and function as a argument explanation

什么是function(json) json参数,是sample.json文件吗?什么是 val 参数?在某些示例中,var 键的外观如何?在此示例代码中,作为参数的函数如何工作?

$.getJSON("sample.json", function(json) {

    json.forEach(function(val) {
    var keys = Object.keys(val);

该函数只是一个回调函数,因此一旦 sample.json 文件被获取并解析,它将 运行 函数内的代码,使用 'json' 作为参考变量

JQuery $.getJSON() 方法的结果是 JavaScript Object Notation 结构。该响应作为第一个参数(在本例中为 json)自动传递给提供的成功回调函数。它不必被称为 json,这只是参数的任意名称,您可以将其称为任何合法的标识符。

接收到参数后,然后使用 .forEach() 遍历结构,其中提供另一个函数作为遍历的每个项目的回调。

Here is the documentation for JQuery's getJSON method.

在该示例中,json 是将传递给 getJSON 回调的第一个参数的参数名称。这将是 解析 和 JSON 的结果(因此不再是 JSON,它将是一个对象图)。

代码期望 JSON 将数组定义为顶级项,并且正在调用 Array.prototype.forEachval 参数——forEach 的第一个参数——将是该数组中按顺序排列的每个元素。

更多内容在 jQuery documentation, on MDN, and in For-each over an array in JavaScript?

$.getJSON("sample.json", function(json) {

$.getJSON得到一个json文件叫"sample.json",这个文件分配在"json" 函数中的变量。

json.forEach(function(val) {

因为JSON是"JavaScript Object Notation",我们知道你的变量json是一个对象, 这就是为什么你可以使用函数 Object.forEach(), 它作为 for..in..,

var keys = Object.keys(val);

Object.keys(val) 这里,你的变量 val 必须是 objectarray,此方法将 return 您的 object/array 中的所有 indexesval), 因此,你在文档 "sample.json" 中引入的 和 json 中的所有 索引将是已添加到 您的变量 keys

例如:

$.getJSON("/json/sample.json", function(json) {

    var html = "";

    json.forEach(function(val) { // Iterates in the json
      var keys = Object.keys(val); // Assignes the indexes to the var keys

      html += "<div>"; // Opens and appends a div element

      keys.forEach(function(key) { // Appends the element of the object/array at each index (key)
        html += "<strong>" + key + "</strong>"
      });

      html += "</div><br>"; // Closes the div element and starts a new line
    });