为什么这个"阵列"不评估为数组?

时间:2016-09-16 23:46:57

标签: javascript angularjs arrays json

我似乎无法弄清楚版本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");
    }

};

1 个答案:

答案 0 :(得分:2)

在版本2中,第一行使用{}设置historyArray - 这会创建一个对象,而不是数组。

相关问题