我似乎无法弄清楚版本2 为什么不作为数组进行评估。句法?
版本1 - 评估为数组:
var historyArray = [];
this.saveHistory = function(question, answer){
historyArray['question'] = historyArray['question'] || [];
historyArray['question'].push(question);
historyArray['answer'] = historyArray['answer'] || [];
historyArray['answer'].push(answer);
if (historyArray instanceof Array){
console.log("array");
console.log(historyArray);
}else{
console.log("not array");
}
};
版本2 - 不评估为数组:
var historyArray = {history:[]};
this.saveHistory = function(question, answer){
historyArray.history.push({
'question' : question,
'answer' : answer
})
var historyLogJSON = JSON.stringify(historyArray);
if (historyArray instanceof Array){
console.log("array");
console.log(historyLogJSON);
}else{
console.log("not array");
}
};
答案 0 :(得分:2)
在版本2中,第一行使用{}设置historyArray - 这会创建一个对象,而不是数组。