JavaScript:类型错误:无法读取未定义的属性“0”

时间:2021-02-02 08:50:11

标签: javascript

for 循环给了我一条错误消息“TypeError:无法读取未定义的属性 '0'” 我该如何解决这个问题?

const ticker = () =>  "msn";
// crypto price data for multiple crypto currencies
function crypto2() {
  var x = ticker().slice(0, 50);
  console.log("x = " + x);
  console.log("ticker length = " + x.length);

  var urlA = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + x + "&tsyms=USD&limit=300";
  var result = null;

  $.ajax({
    url: urlA,
    async: false, // makes a synchrously data call to cryptocompare
    dataType: "json",
    success: function(data) {
      result = data;
    }
  });

  var y = result;
  console.log("y = " + JSON.stringify(y));
  console.log("y.BTC = " + y.BTC.USD);
  console.log("rght = " + JSON.stringify(x[0]));

  var D1 = [];
  for (var i = 0; i < 40; i++) {
    D1.push(y.x[i].USD);
  }
  // console.log("data = " + D1);
  return D1;
}
crypto2()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:2)

您没有 x[0] 也没有 y.BTC.USD

你可以使用这个语法

D1.push(y?.x?.[i].USD);

但我会使用地图

const ticker = () =>  ["eth","doge","btc"];
// crypto price data for multiple crypto currencies
function crypto2() {
  var x = ticker().slice(0, 50);
  console.log("x = " + x);
  console.log("ticker length = " + x.length);

  var urlA = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + x + "&tsyms=USD&limit=300";
  var result = null;

  $.ajax({
    url: urlA,
    async: false, // makes a synchrously data call to cryptocompare
    dataType: "json",
    success: function(data) {
      result = data;
    }
  });

  console.log("result = " + JSON.stringify(result));

  const D1 = Object.keys(result).map(key => result[key]?.["USD"])
  return D1;
}
console.log(crypto2())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

和异步

const ticker = () =>  ["eth","doge","btc"];
// crypto price data for multiple crypto currencies
function crypto2() {
  var x = ticker().slice(0, 50);
  console.log("x = " + x);
  console.log("ticker length = " + x.length);

  var urlA = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + x + "&tsyms=USD&limit=300";
  var result = null;

  $.ajax({
    url: urlA,
    dataType: "json",
    success: function(data) {
      const D1 = Object.keys(data).map(key => data[key]?.["USD"])
      console.log(D1);
    }
  });
}
crypto2()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>