Javascript forEach不适用于json

Javascript forEach is not working for json

本文关键字:json 适用于 不适用 forEach Javascript      更新时间:2023-09-26

我有一个ajax,有时会像一样返回数据

{
    "results": [{
        "symbol": "AppConomy",
        "Name": null,
        "PriceSales": null
    }]
}

对于上面我的forEach函数工作正常,但当相同的数据返回时

 {
     "results": {
         "symbol": "AppConomy",
        "Name": null,
        "PriceSales": null
    } 
}

我的forEach函数不工作

 $.get(url, function(data){
        var x =data['results'];
        x.forEach(function logArrayElements(element, index, array) {
           $(self).append('<button class="tag-format" title="'+array[index].Name+'"  style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;">&nbsp;'+ array[index].symbol +" - "+ array[index].PriceSales +'&nbsp;</button>');
        });
     });

这是因为JSON不是数组。您可以使用Array.isArray()轻松地预先检查。如果您检索的数据实际上是JSON,则也应该使用getJSON

$.getJSON(url, function(data) {
    var x = data.results;
    if(Array.isArray(x)) {
        x.forEach(function logArrayElements(element, index, array) {
            $(self).append('<button class="tag-format" title="' + array[index].Name + '"  style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;">&nbsp;' + array[index].symbol + " - " + array[index].PriceSales + '&nbsp;</button>');
        });
    } else {
        $(self).append('<button class="tag-format" title="' + x.Name + '"  style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;">&nbsp;' + x.symbol + " - " + x.PriceSales + '&nbsp;</button>');
    }
});

您的forEach用于在数组上迭代。在第二个JSON中,没有可迭代的数组,因此需要直接在data['results']:上调用函数

$.get(url, function(data){
  var x = data['results'],
      addButton = function(item) {
        $(self).append('<button class="tag-format" title="'+array[index].Name+'"  style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;">&nbsp;'+ array[index].symbol +" - "+ array[index].PriceSales +'&nbsp;</button>');
      };
  if(Array.isArray(x)) {
    x.forEach(function logArrayElements(element, index, array) {
      addButton(array[index]);
    });
  } else {
    addButton(x);
  }
});

Javascript对象不是Array。

Html

<div id="results"></div>

Javascript

var firstArray = {
"results": [{
    "symbol": "AppConomy",
    "Name": null,
    "PriceSales": null
}]};
var secondArray =  {
 "results": {
     "symbol": "AppConomy",
    "Name": null,
    "PriceSales": null
}};
//Result: 1
$("#results").append("<span>FirstArray result: " + firstArray['results'].length + "</span><br/>");
//Result: undefined
$("#results").append("<span>FirstArray result: " + secondArray['results'].length + "</span><br/>");