$.each() 添加“未定义”值

$.each() adds "undefined" value

本文关键字:未定义 添加 each      更新时间:2023-09-26

下面的代码工作得很好,除了在附加从 JSON 多维数组动态检索的元素时得到的烦人的未定义。我无法弄清楚它来自哪里,但是,我认为它来自在函数外部声明一个变量并在$.each()内部使用它来积累数据。

var c = 0;
var q = 1;
$.each(json, function (i, data) {
  var answers; // declared here and outside this function - same results.
  $.each(data.answers, function (i, a) {
    answers += '<tags>' + a + '</tags>'; // the problem is here "maybe".
  });
  $('.foo').append(answers); // I get "undefined" ahead of values retrieved.
});

操场

您在结果之前会得到"未定义",因为您使用+=并从未定义的answers变量开始。

尝试声明var answers = ''; .