我的对象文字有一个info属性,其值是一个数组。我正在尝试将新数据推送到该数组中,使用对象文字上的每个函数来确保我正在更新正确的目标。
这是一个小提琴:http://jsfiddle.net/charliemagee/ZZwnN/
控制台显示未捕获的TypeError:对象['66','77']没有方法'push'
但是之前的console.log显示它是一个数组,所以push应该可以工作,对吗?
这是对象文字的一部分。
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"
}
}
这是推动阵列的功能。
$(".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();
});
答案 0 :(得分:2)
如果您将控制台日志更改为console.log(typeof(goal.info));
,您将看到它是一个字符串,而不是一个数组。删除引号,它工作正常:
"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"
},