2016-09-16 5 views
-4

なぜバージョン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 - 配列として評価されない:バージョン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"); 
    } 

}; 
+3

historyArrayを{} .....のオブジェクトにしました..... – ASDFGerte

+0

[MCVE]ガイダンスを読んでください - このポストのコードを 'if({instanceof Array} {{ (残念なことに副作用はおそらく質問として投稿するのではないでしょうが、時にはSOに投稿しても大丈夫です) –

答えて

3

、非常に最初の行はhistoryArrayを設定します{}を使用すると、配列ではなくオブジェクトが作成されます。

関連する問題