$ .each()添加“未定义"价值 [英] $.each() adds "undefined" value

查看:119
本文介绍了$ .each()添加“未定义"价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码可以正常工作,除了在添加从 JSON多维数组动态获取的元素时出现的令人讨厌的 undefined .我无法弄清楚它的来历,但是,我认为它来自于在函数外部声明一个变量并在$.each()内部使用它来累积数据.

The below code works just fine except for the annoying undefined I am getting when appending elements dynamically retrieved from a JSON multidimensional array. I could not figure out from where it is coming, however, I assume it is coming from declaring a variable outside function and using it inside $.each() to accumulate data.

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.
});

游乐场

Playground

推荐答案

由于使用+=并以未定义的answers变量开头,因此您会在结果之前获得未定义".

You get 'undefined' ahead of your results because you use += and start with an undefined answers variable.

尝试声明var answers = '';.

这篇关于$ .each()添加“未定义"价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆