【问题标题】:Why is this "array" not evaluating as an Array?为什么这个“数组”不评估为数组?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2015-07-02
    • 2015-03-18
    • 2013-10-20
    相关资源
    最近更新 更多