如何解决 TypeError: Cannot conversion undefined or null to object with node.Js

问题描述 投票:0回答:1

我想创建一个程序,如果 'Bab' 的值为 null,则 babParagraph 将不会出现。但是,当我创建以下条件语句时,我遇到一条错误消息:“无法将未定义或 null 转换为对象”。 PS:我使用docx

这是我的代码片段:

let babParagraph = null; // Initialize babParagraph with null

        // check if item.bab isn't null
        if (item.bab !== null) {
            // if item.bab isn't null, create babParagraph
            babParagraph = new Paragraph({
                children: [
                    new docx.TextRun({
                        text: 'Bab ' + item.bab,
                    }),
                    new docx.TextRun({
                        text: '\nKetentuan Umum',
                        break: 1,
                    }),
                ],
                alignment: AlignmentType.CENTER,
            });
        }

然后出现错误:

var _name = Object.keys(value)[0];
                           ^
TypeError: Cannot convert undefined or null to object
 at Function.keys (<anonymous>)
    at d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18745:32 
    at Array.forEach (<anonymous>)
    at resolve (d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18743:1618743:16)
    at d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18749:28 
    at Array.forEach (<anonymous>)
    at resolve (d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18743:1618743:16)
    at d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18749:28 
    at Array.forEach (<anonymous>)
    at resolve (d:\magang\json_ke_word\node_modules\docx\build\index.cjs:18743:1618743:16)

Node.js v20.11.1
javascript node.js null typeerror docx
1个回答
0
投票

试试这个。

if (item.bab != ''){
}
or if(typeof item.bab === undefined){
}
© www.soinside.com 2019 - 2024. All rights reserved.