当我警告下面例子中的输出时,我得到了正确的输出,但是当我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;
});
});
发布于 2019-11-04 14:36:24
这个问题是因为您正在使用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)对object使用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>
我更喜欢后一种方法,但它们中的任何一种都可以工作。
https://stackoverflow.com/questions/58695516
复制相似问题