Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我会得到';未定义';在控制台里?_Javascript_Jquery - Fatal编程技术网

Javascript 为什么我会得到';未定义';在控制台里?

Javascript 为什么我会得到';未定义';在控制台里?,javascript,jquery,Javascript,Jquery,这是我的密码: var textArray = ['#text1', '#text2', '#text3', '#text4', '#text5', '#text6', '#text7', '#text8'] $('#capture').click(function() { for (var i in textArray) { console.log($(i).offset()); } }); 不知道为什么我在控制台中没有定义。我觉得我遗漏了一些非常简单的东西。因

这是我的密码:

var textArray = ['#text1', '#text2', '#text3', '#text4',
'#text5', '#text6', '#text7', '#text8']

$('#capture').click(function() {
    for (var i in textArray) {
      console.log($(i).offset());
    }
});

不知道为什么我在控制台中没有定义。我觉得我遗漏了一些非常简单的东西。

因为
I
是数组中项目的索引,您需要使用
textary[I]
访问当前项目(如果您记录了
I
的值,它将显示0,1,2…7)


您可能希望像这样对数组进行索引:

var textArray = ['#text1', '#text2', '#text3', '#text4',
'#text5', '#text6', '#text7', '#text8']

$('#capture').click(function() {
for (var i in textArray) {
  console.log($(textArray[i]).offset());
}
});

JavaScript中的
for…in
循环遍历对象的键,而不是对象的值。如果支持,您可以使用
Array.prototype.forEach
<代码>$。由于您使用的是jQuery,因此每个也都可以作为备用

var textArray = ['#text1', '#text2', '#text3', '#text4',
                 '#text5', '#text6', '#text7', '#text8'];

$('#capture').click(function() {
    textArray.forEach(function (x) {
        console.log($(x).offset());
    });
});

您不应该在中使用
for..在数组上循环。这意味着在对象上循环
{}

下面使用

$('#capture').click(function() {
    $.each(textArray, function(value) {
        console.log($(value).offset());
    })
});

您可以使用
Array#forEach
,但IE8不支持
forEach
,所以我使用jQuery的
每个

简单调试:
console.log(I)这是您所期望的吗?
$('#capture').click(function() {
    $.each(textArray, function(value) {
        console.log($(value).offset());
    })
});