Why am I getting 'undefined' in console?

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • 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

    上一篇: 如何为每个循环创建一个JavaScript

    下一篇: 为什么我在控制台中获得'未定义'?