TypeError: "x" is (not) "y"
JavaScript å¼å¸¸âx is (not) yâå¨åºç°ä¸ææä¸ç¬¦çç±»åï¼é常为æå¤è·å¾ç undefined æ null å¼ï¼æ¶è¢«æåºã
æ¶æ¯
TypeError: Cannot read properties of undefined (reading 'x') (V8-based) TypeError: "x" is undefined (Firefox) TypeError: "undefined" is not an object (Firefox) TypeError: undefined is not an object (evaluating 'obj.x') (Safari) TypeError: "x" is not a symbol (V8-based & Firefox) TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
é误类å
TypeErrorã
ä»ä¹å°æ¹åºéäºï¼
åºç°äºä¸ææä¸ç¬¦çç±»åãè¿ä¸ªéè¯¯å¸¸å¸¸ç± undefined æ null å¼å¼èµ·ã
æ¤å¤ï¼æäºæ¹æ³ï¼ä¾å¦ Object.create() æ Symbol.keyFor()ï¼è¦æ±å¿
é¡»æä¾ç¹å®ç±»åçåæ°ã
示ä¾
>é误æ å½¢
js
// undefined and null cases on which the substring method won't work
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined
const foo = null;
foo.substring(1); // TypeError: foo is null
// Certain methods might require a specific type
const foo = {};
Symbol.keyFor(foo); // TypeError: foo is not a symbol
const foo = "bar";
Object.create(foo); // TypeError: "foo" is not an object or null
è§£å³æ¹æ³
è¦è§£å³å¼ä¸º undefined æ null ç空æéé®é¢ï¼ä½ å¯ä»¥é¦å
æµè¯å¼æ¯å¦ä¸º undefined æ nullã
js
if (foo !== undefined && foo !== null) {
// Now we know that foo is defined, we are good to go.
}
æè
ï¼ä½ 妿è½ç¡®å® foo çå¼ä¸ä¼æ¯å
¶ä»çåå¼ï¼å¦ï¼"" æ 0ï¼ï¼æè
æé¤è¿äºæ
åµä¸æ¯é®é¢ï¼é£ä½ å¯ä»¥ç®åå°æµè¯å
¶æ¯å¦ä¸ºçã
js
if (foo) {
// Now we know that foo is truthy, it will necessarily not be null/undefined.
}