1

Why does this each statement cause my code to break? Also do I have to set an index with javascript?

var email = [];

email['update'] = true;
email['e_case_id'] = $("#e_case").val();

var i = 0;

$.each($('.rowChecked'), function() {
    email['e_attachments'][i] = $(this).attr('id');
    i++;
});
8
  • do you get any errors in console? Also, .each's function can take index, value, so you don't really even need that i++ in there. just declare function(i, v){ ... } Commented May 14, 2013 at 20:27
  • Javascript does not support associative arrays. So you can not simply do email['update'] = true; As discussed in some answers below you can use a literal object like an associative array: myLiteralObject = {}; myLiterObject["associativeStyleKey"] = "whatever"; Commented May 14, 2013 at 20:32
  • @Mike: actually it would work anyway because an Array is also an object. Commented May 14, 2013 at 20:33
  • except the code looks like it's trying to iterate through a list of attachments. This doesn't look right Commented May 14, 2013 at 20:35
  • @Claudiu: Yes, it works until you try to loop through the array, as the each method will only loop through the array items, not the object properties. Commented May 14, 2013 at 20:35

1 Answer 1

8

Firstly, email should be an object literal, not an array literal:

var email = {};

Secondly, you didn't define email['e_attachments'] before you tried to use it. This is likely what's prevent it from working. Try adding

email['e_attachments'] = [];

Before the $.each.


You can use $.map in this circumstance, btw. That is:

email['e_attachments'] = $.map($('.rowChecked'), function (el) { 
    return $(el).attr('id'); 
});

Instead of your $.each. Or better yet:

email['e_attachments'] = $('.rowChecked').map(function () { 
    return $(this).attr('id'); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.