【发布时间】:2016-09-16 23:46:56
【问题描述】:
我似乎无法弄清楚为什么 第 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");
}
};
【问题讨论】:
-
因为你用 {}..... 将 historyArray 变成了一个对象
-
请阅读minimal reproducible example 指导——它可以帮助你将这篇文章的代码缩小到
if ({} instanceof Array){...(不幸的副作用是你可能不会把它作为问题发布——但有时它是可以的不要在 SO 上发帖)
标签: javascript angularjs arrays json