简体   繁体   English

需要 fetch() 等的 JavaScript 示例

[英]Need JavaScript example for fetch() etc

I want to learn such new JavaScript features as fetch() and arrow functions.我想学习诸如 fetch() 和箭头函数之类的新 JavaScript 功能。 To this end, I selected a function from a recent app, and attempted to replace older features with new.为此,我从最近的应用程序中选择了一个功能,并尝试用新功能替换旧功能。 Very little success.成功率极低。 Here's my original function:这是我的原始功能:

function popNames(arNumbers,ctrlName) {
  var arSortedList = [];
  var strNameList = "";
  $.getJSON("NAME.json").done(function(zdata) {
$.each(arNumbers, function(i, ydata) {
  $.each(zdata.NAME, function(k,v) {
    if(v.idName == ydata) {// important: === did NOT work
          if(ctrlName) arSortedList.push(v.last + ", " + v.first + ";" + v.idName);
      else arSortedList.push(v.last + ", " + v.first);
    }
  });   // each element of NAME.json
}); // each idName value in the array passed
if(ctrlName) {
  setOptions(arSortedList, ctrlName);
} else {
  strNameList = arSortedList.join();
}
  });   // getJSON NAME
}

I was successful using this line:我成功地使用了这条线:

fetch("NAME.json").then(zdata => zdata.json())

but nothing I did after that worked.但在那之后我所做的一切都没有奏效。 I'd appreciate seeing an example from which I can learn.我很高兴看到一个我可以学习的例子。

function popNames(arNumbers,ctrlName) {
    let arSortedList = [];
    let strNameList = "";
    fetch("NAME.json").then(zdata => zdata.json())
    .then(zdata => {
        for(const ydata of arNumbers)   {
            for(const v of zdata.NAME) {
                if(v.idName == ydata) {     // important: === did NOT work
                    if(ctrlName) arSortedList.push(v.last + ", " + v.first + ";" + v.idName);
                    else arSortedList.push(v.last + ", " + v.first);
                }
            }
        }
        if(ctrlName) {
            setOptions(arSortedList, ctrlName);
        } else {
            strNameList = arSortedList.join();
        }
    }); // getJSON NAME
}

I was researching why I couldn't next two Array.forEach statements, and discovered a new iterable construction (for...of).我正在研究为什么我不能下两个 Array.forEach 语句,并发现了一个新的可迭代结构(for...of)。

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

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