当我在下面的例子中警告输出时,我得到正确的输出,但当我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( 使用传递给函数的参数,而不是this
引用:
var foo = { "width": [ 25, 50, 75, 100 ] }
jQuery.each(foo.width, function(i, value) {
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2( 对对象使用toString()
或valueOf()
。旁注,问题中的alert()
之所以有效,是因为它在引擎盖下调用toString()
。
var foo = { "width": [ 25, 50, 75, 100 ] }
jQuery.each(foo.width, function() {
console.log(this.toString());
console.log(this.valueOf());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
3( 不要使用jQuery循环遍历一个简单的值数组。使用forEach()
循环:
var foo = { "width": [ 25, 50, 75, 100 ] }
foo.width.forEach(function(value) {
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
我更喜欢后一种方法,但其中任何一种都有效。