在“for...of”循环中无法读取超出第一次迭代的内容/迭代为空

我有一个数组,questionsArray,我需要在该数组中的每个问题中做一些事情。第一次迭代有效,但除此之外,它说它无法读取 null 的属性 x。这是为什么?- 这是遍历数组的代码:


var insertion = new Promise(async (resolve, reject) => {

                    for(const question of questionsArray){

                        await db.query('INSERT INTO `ml-questions-data` (`text`, `status`, `question_id`, `answer_text`, `answer_status`, `answer_date`, `item_id`, `seller_id`, `created`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',

                         [question.text, question.status, question.id, question.answer.text, question.answer.status, question.answer.date_created, question.item_id, question.seller_id, question.date_created], (erro)=>{

                            if(erro){

                                reject(erro)

                            }

                            else{

                                console.log('array iteration! db insertion')

                            }

                        })

                    }

                    resolve()

                });

-这是questionsArray数据:


[

    {

        "date_created": "2019-09-30T03:18:08.000-04:00",

        "item_id": "MLB1329418290",

        "seller_id": 158369990,

        "status": "ANSWERED",

        "text": "olá, gostaria de entender como funciona isso?",

        "id": 6553335409,

        "deleted_from_listing": false,

        "hold": false,

        "answer": {

            "text": "pois bem, vamos adicionar um texto de resposta no json",

            "status": "ACTIVE",

            "date_created": "2019-09-30T03:24:52.120-04:00"

        },

        "from": {

            "id": 444188609,

            "answered_questions": 2

        }

    },

    {

        "date_created": "2019-09-30T03:22:21.000-04:00",

        "item_id": "MLB1329418290",

        "seller_id": 158369990,

        "status": "BANNED",

        "id": 6553335807,

        "deleted_from_listing": false,

        "hold": false,

        "answer": null,

        "from": {

            "id": 444188609,

            "answered_questions": 2

        }

    },


    the array goes on.....

]


手掌心
浏览 129回答 2
2回答

慕村225694

“answer”在数组的第二个元素中为空,因此您无法访问 question.answer.text。(在数组的第一个元素中,answer 是一个带有名为“text”的元素的映射)。对于尝试访问其成员的插入的所有部分,您将需要处理输入数组中 answer 为空的情况。

神不在的星期二

检查question.answer?question.answer.text : ""所以基本上这是对answer object的空检查。所以如果 answer 不为 null 那么它只会执行question.answer.text否则它将给出/分配“”空值
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript