使用jquery遍历json数据

在下面的示例中警告输出时,我得到正确的输出,但是当我console.log输出时,我得到:Number {}

"width": [ 25,50,75,100 ],jQuery.each(width,function() {
  new_width = this;
  console.log(new_width);
  alert(new_width);
  document.querySelectorAll('#source').forEach(function (element,index) {
    element.style.width = new_width;
  });
});
banqiansheng 回答:使用jquery遍历json数据

问题是因为您使用html,body{overflow-x: hidden;} 遍历数组。通过jQuery.each()访问时,您收到一个this对象,而不是整数值,因此将Number输出到日志。有几种方法可以解决此问题:

1)使用传递给函数的参数代替{}引用:

this
var foo = { "width": [ 25,50,75,100 ] }
jQuery.each(foo.width,function(i,value) {
  console.log(value);
});

2)在对象上使用<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>toString()。旁注,您问题中的valueOf()之所以有效,是因为它在幕后叫alert()

toString()
var foo = { "width": [ 25,function() {
  console.log(this.toString());
  console.log(this.valueOf());
});

3)不要使用jQuery遍历简单的值数组。使用<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>循环:

forEach()
var foo = { "width": [ 25,100 ] }
foo.width.forEach(function(value) {
  console.log(value);
});

我更喜欢后一种方法,但是其中任何一种都可以。

本文链接:https://www.f2er.com/3165976.html

大家都在问