【问题标题】:Array is not an Array [closed]数组不是数组[关闭]
【发布时间】:2017-10-02 16:48:50
【问题描述】:

我有一个看起来像数组的对象

var questions = 

[ { started_time: 2017-05-04T12:46:39.439Z,
    word: 'bottle',
    questionId: '161013bd-00cc-4ad1-8f98-1a8384e202c8' },
  { started_time: 2017-05-04T12:47:26.130Z,
    word: 'play',
    questionId: 'a84bd1b4-8b9c-4ec7-862d-ba994ac1f371' },
  { started_time: 2017-05-04T12:47:50.156Z,
    word: 'bottle',
    questionId: '4c7e1ee8-651e-4086-8e69-ce64414a815a' },
  { started_time: 2017-05-04T12:54:40.703Z,
    word: 'was',
    questionId: '79412420-eee9-47e0-8fb8-d854c5889765' },
  { started_time: 2017-05-04T12:55:36.474Z,
    word: 'liked',
    questionId: '525d90c9-4cca-433c-99c5-56bb54756b9c' } ]

我正在尝试创建一个这样的单词数组:

["bottle", "play", "was", "liked"]

当我尝试 questions.map(etc..) 时,我得到了

TypeError: questions.map is not a function

而 Array.isArray(questions) 是假的

我不知道为什么我不能把它当作一个数组。任何帮助将不胜感激。

【问题讨论】:

  • 假设 started_time 值在您的实际代码中以某种方式分隔,而不是像上面那样未封闭,这不仅仅是 看起来 像一个数组,它是一个数组:jsfiddle.net/9Lgt5abm 如果不是,那可能有点问题,因为它们是语法错误,但很难看出你是如何得到 that 错误的这种情况下的消息。
  • 当我将您的代码按原样粘贴到 Chrome 开发工具中时,我收到一个错误,因为每个 started_time 都无效。这些需要是字符串或 Date 对象。
  • 执行该分配会引发语法错误,started_time 应该是一个字符串,因此每个值都应该在引号之间

标签: javascript arrays node.js mongoose ecmascript-6


【解决方案1】:

var question = [ 
            { 
            started_time: '2017-05-04T12:46:39.439Z',
            word: 'bottle',
            questionId: '161013bd-00cc-4ad1-8f98-1a8384e202c8' 
            },
            {
            started_time: `2017-05-04T12:47:26.130Z`,
            word: 'play',
            questionId: 'a84bd1b4-8b9c-4ec7-862d-ba994ac1f371'
            }
          ];


//console.log(JSON.stringify(question) + "<br>");

var result = question.map(function(x){
  return x.word;
});

console.log(result);

【讨论】:

  • 反对者,请给我留言。我给出了简单易懂的解决方案。
  • 如果我的解决方案解决了您的新阵列问题,请告诉我。
  • 仍然有这个问题,我删除了日期。 Mongoose 正在返回一个看起来像数组但不是的对象: var query = Challenges.findOne({"_id":newQuestion.challengeId}).select('question.word') query.exec(function (err, questions ){` var questionsNoDate = questions.question` console.log(typeof(questionsNoDate))` console.log(Array.isArray(questionsNoDate))` console.log(questionsNoDate)` 返回:object false [ { word : 'honest' }, { word: 'bottle' }, { word: 'bottle' } ] 如何将其转换为普通数组?
  • 修复了!!!需要将 .lean() 添加到我的 Mongoose 查询中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 2021-02-03
  • 2015-03-23
  • 2021-01-31
相关资源
最近更新 更多