源自TypeError Cannot [call method / read property / set property] of null in Google Apps Script 的规范问题
建议参考以下问题:
- Why the 项目中GS文件的执行顺序 causes
TypeError: Cannot read property "sayName" from undefined.
?
-
测试触发器 causes
ReferenceError: 'e' is not defined.
or TypeError: Cannot read property *...* from undefined
- 类型错误:无法从未定义中读取属性“0”
-
Google Script send form values by email, error: cannot read property "namedValues"
Not enough details from the OP but three different answers that for different scenarios
- 类型错误:无法调用未定义的方法“getName”
-
TypeError: Cannot read property 'value' of undefined (line 3, file "Code"). I have a trigger for on form submit and yet it still has an errorMissing character in property name (OP used value instead of values)
描述
该错误消息表明您正在尝试访问Object
实例,但期间runtime价值actually变量所持有的是一种特殊的数据类型undefined
.
See key terms definition at the bottom.
Causes:
const obj = {a:1};
const b = obj.b;//undefined because b isn't available on obj. But doesn't throw a error
console.log(b.toString())//Throws type error
const a = [[1],[2],[3]];
const getElement3 = a[3];//undefined,because `3`'s index is ``2`` not `3`;But doesn't throw a error
console.log(getElement3[0])//Throws type error
错误是一个类型错误因为一个"object"
是预期的,但是"undefined"
已收到
怎么修
-
使用默认值
空合并运算符 ??
JavaScript 中的运算符如果左侧是,则计算右侧null
or undefined
。像这样的表达(myVar ?? {}).myProp
(or (myVar ?? [])[index]
对于数组)将保证不会抛出错误,如果该属性至少是undefined
.
还可以提供默认值:(myVar ?? { myProp : 2 })
保证访问myProp
回来2
默认情况下。数组也是如此:(myVar ?? [1,2,3])
.
-
检查类型
对于特殊情况尤其如此,typeof
operator结合一个if
陈述 and a 比较运算符将允许函数在其指定上下文之外运行(即出于调试目的)或根据对象是否存在引入分支逻辑。
人们可以控制检查的严格程度:
- 宽松(“未定义”):
if(typeof myVar !== "undefined") { //do something; }
- 严格(“仅限适当的对象”):
if(typeof myVar === "object" && myVar) { //do stuff }
关键术语
- Object
- It's one of the JavaScript data types.
- undefined
- It's one of the JavaScript primitive data types.
要了解 JavaScript 数据类型和对象的基础知识,请参阅JavaScript 数据类型是什么? and 到底什么是对象? [JavaScript].
Original revision extracted from here (Credit to @OlegValter)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)