1

我有以下代码:

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 很陌生,发现它有点棘手。它坏了的原因是什么,我该如何修复它?

4

3 回答 3

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 ) {
        // ...
    });
}
于 2013-06-28T23:04:06.443 回答
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();
}
于 2013-06-28T22:41:55.667 回答
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'
  }
]
于 2013-06-28T22:42:33.633 回答