jQuery变量范围?说未定义

时间:2013-06-28 22:39:38

标签: javascript jquery

我有以下代码:

function postToDrupal(contacts, source, owner) {
  (function ($) {

    var contact, name, email, entry;
    emails = {};

    for (var i = 0; i < contacts.length; i++) {
      contact = contacts[i];
      emails[i]['name'] = contact.fullName();
      emails[i]['email'] = contact.selectedEmail();
    }

    $.post("/cloudsponge-post",emails,function(data) {

    });
  }(jQuery));
}

尝试运行时出现以下错误:

WARN: Attempt to invoke callback [afterSubmitContacts] failed: TypeError: Cannot set property 'name' of undefined

我不确定问题是什么 - 我对JS很新,发现它有点棘手。它被破坏的原因是什么,我该如何修复它?

3 个答案:

答案 0 :(得分:3)

您可以通过多种方式编写此代码,但我个人会这样做:

function postToDrupal( contacts, source, owner ) {
    // TODO: source and owner are unused

    var emails = jQuery.map( contacts, function( contact ) {
        return {
            name: contact.fullName(),
            email: contact.selectedEmail()
        }
    });

    jQuery.post( '/cloudsponge-post', emails, function( data ) {
        // ...
    });
}

答案 1 :(得分:2)

尚未定义该对象emails[i]。试试这个:

for (var i = 0; i < contacts.length; i++) {
  contact = contacts[i];
  emails[i] = {}; //Instantiate it here
  emails[i]['name'] = contact.fullName();
  emails[i]['email'] = contact.selectedEmail();
}

答案 2 :(得分:0)

我怀疑你想要一个数组而不是一个对象。因此,您应该将emails = {}更改为emails = []

如果按照@PSL的建议,你会以这样的对象(不是数组)结束:

{
  0: {
    name: 'john'
    email: 'john@john.com'
  },
  1: {
    name: 'lennon'
    email: 'lennon@lennon.com'
  }
}

一种可能的解决方案:

var contact, name, email, entry,
  emails = [];

for (var i = 0; i < contacts.length; i++) {
  contact = contacts[i];
  emails.push({name: contact.fullName(), email: contact.selectedEmail()});
}

你最终会得到这个:

[
  {
    name: 'john'
    email: 'john@john.com'
  }
  ,{
    name: 'lennon'
    email: 'lennon@lennon.com'
  }
]