使用jquery迭代json数据
当我在下面的示例中警告输出时,我得到了正确的输出,但是当我使用jquery迭代json数据,jquery,json,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
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;
});
});
问题是因为您正在使用
jQuery.each()
在数组中循环。通过this
访问时,您会收到一个Number
对象,而不是一个整数值,因此{}
输出到日志。有几种方法可以解决此问题:
1) 使用传递给函数的参数,而不是此
引用:
var foo={“宽度”:[25,50,75,100]}
每个(foo.width,函数(i,值){
console.log(值);
});代码>
一个更简单的解释是执行上下文中的“this”是js对象。您需要每个项目的实际值,因此您需要使用“each”函数参数(第一个是索引,第二个是实际值)。一个更简单的解释是,执行上下文中的“this”是您所指的js对象
?它是一个Number
对象,正如我在答案中解释的那样。循环构造函数对象。我知道你解释得很详细,我只是投票赞成详细的解释,并试图缩短解释。