My object literal has an info property with a value that is an array. I'm trying to push new data into that array, using an each function on the object literal to make sure I'm updating the correct goal.

Here's a fiddle: http://jsfiddle.net/charliemagee/ZZwnN/

Console shows Uncaught TypeError: Object ['66','77'] has no method 'push'

But the previous console.log shows that it is an array, so push should work, right?

Here's a section of the object literal.

goals = {

  "9e693231-e6d8-4ca9-b5c8-81ea7a8dd54": {
    category: "school",
    datecreated: "2013-10-20",
    goal: "keep locker tidy",
    icon: "clipboard",
    status: "inprogress",
    infotype: "text",
    info: "['66','77']",
    recurring: "mon,wed,fri",
    complete: "Great Job!",
    deadline: "2014-1-20",
    username: "maryjones",
    userguid: "0c7270bd-38e8-4db2-ae92-244de019mju7"
  }
}

And here's the function that's supposed to push the array.

$(".goalsinprogress").delegate("input[type=checkbox]", "click", function() {
  goalguid = $(this).parent().parent().data("goalguid");
  emailGoal = $(this).parent().data('goal');
  newinfo = $(this).closest('li').find('input[type="text"]').val();
  $(this).parent().parent().removeClass("inprogress missed").addClass("completed").prop("checked", true);
  updateStatus = 'completed';
  $.each(goals, function(index, goal) {
    if (index === goalguid) {
      console.log(goal.info); // shows that goal.info is an array
      goal.info.push(newinfo); // gives me the error
      console.log(goal.info);
      goal.status = updateStatus;
      return false;
    }
  });
  localStorage.setItem("goals", JSON.stringify(goals));
  $(this).find('.info').hide();
  $(this).find('.info').val('');
  return displayMyGoalList();
});
有帮助吗?

解决方案

If you change the console log to console.log(typeof(goal.info)); you'll see it is a string, not an array. Remove the quotes and it works fine:

  "9e693231-e6d8-4ca9-b5c8-81ea7a8dd54": {
    category: "school",
    datecreated: "2013-10-20",
    goal: "keep locker tidy",
    icon: "clipboard",
    status: "inprogress",
    infotype: "text",
    info: ['66','77'],  // no quotes here
    recurring: "mon,wed,fri",
    complete: "Great Job!",
    deadline: "2014-1-20",
    username: "maryjones",
    userguid: "0c7270bd-38e8-4db2-ae92-244de019mju7"
  },
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top