Why am I getting 'undefined' in console?
This question already has an answer here:
A for…in
loop in JavaScript loops through an object's keys, not its values. You can use Array.prototype.forEach
, given support; $.each
works as a fallback too, since you're using jQuery.
var textArray = ['#text1', '#text2', '#text3', '#text4',
'#text5', '#text6', '#text7', '#text8'];
$('#capture').click(function() {
textArray.forEach(function (x) {
console.log($(x).offset());
});
});
因为i
是数组中项目的索引,所以您需要使用textArray[i]
来访问当前项目(如果您记录了i
的值,它将显示0,1,2 ... 7)。
for (var i in textArray) {
console.log($(textArray[i]).offset());
}
您可能想要像这样索引数组:
var textArray = ['#text1', '#text2', '#text3', '#text4',
'#text5', '#text6', '#text7', '#text8']
$('#capture').click(function() {
for (var i in textArray) {
console.log($(textArray[i]).offset());
}
});
链接地址: http://www.djcxy.com/p/12062.html
下一篇: 为什么我在控制台中获得'未定义'?