2013-06-20 58 views
1

我一直得到Uncaught TypeError: Cannot set property '0' of undefined,但我不能为我的生活弄清楚什么是错的!Uncaught TypeError:无法设置属性'0'的未定义

var anchor = []; 
getAnchors(); 
function getAnchors() { 
    $('.anchor').each(function(i) { 
     anchor[i] = $(this).offset().left; 
    }); 
} 

那么这段代码有什么问题? 我已经将anchor声明为一个数组。 我一直在检查一个小时的愚蠢错别字。 错误在于i。但是是什么的错误?

编辑: I found out what's wrong.

+1

第一个问题我注意到您正在将非索引键分配给数组。你的意思是'anchor [i] = {}'? – elclanrs

+1

一个数组没有这样的键,你正在寻找一个对象 – adeneo

回答

1

您可以使用$.map构建阵列:

var anchor; 
function getAnchors() { 
    anchor = $.map($('.anchor'), function(el) { return $(el).offset().left; }); 
} 
1

尝试返回数组呢?像这样:

function getAnchors() { 
    var allAnchors = []; 
    $('.anchor').each(function(i) { 
     allAnchors.push($(this).offset().left); 
    }); 
    return allAnchors; 
} 

var anchor = getAnchors(); 
1

您需要在为其分配值之前创建对象属性。

var anchor = []; 
    $('.anchor').each(function(i) { 
     anchor[i] = [{ 
      pos: null, 
      id: null 
     }]; 
     anchor[i]['pos'] = $(this).offset().left; 
     anchor[i]['id'] = $(this).attr('id'); 
    }); 

然后进行赋值并用您的值覆盖null。

0

你可以这样做:

var anchors = $('.anchor').map(function() { 
    return { 
    pos: $(this).offset().left, 
    id: this.id 
    } 
}).get(); 
1

我找到了答案。我只是不得不在函数中声明anchor

getAnchors(); 
function getAnchors() { 
    var anchor = []; 
    $('.anchor').each(function(i) { 
     anchor[i] = $(this).offset().left; 
    }); 
    // perhaps sort anchor 
    console.log(anchor); 
} 

感谢您的回复。

+0

做TBH没有意义。如果这是您需要的,请检查@ adaneo的答案。 – elclanrs

相关问题