ãªãã¸ã§ã¯ããnullãundefindã§ãªããè©ä¾¡ããã
ifã§è©ä¾¡ããã°ä¸çºã§å¤å®ã§ãã¾ãã
if ( !target ) { ... } // 以ä¸ã®ããã«ã¯ããªãã¦ãããã // if ( target == null || target == undefined ) { ... }
å¤ãã¨ã®ifã§ã®è©ä¾¡çµæã¯æ¬¡ã®è¡¨ã®éãã空æååã0ã¯falseæ±ããªã®ã§æ³¨æã
å¤ | ifã§è©ä¾¡ããçµæ |
---|---|
Object | true |
undefined | false |
null | false |
0 | false |
1 | true |
-1 | true |
""(空æåå) | false |
"a" | true |
é å | true |
ããã·ã¥ | true |
確èªãã¦ã¿ã¾ãã
var stdout = document.getElementById("stdout"); // ãªãã¸ã§ã¯ã / null, undefind 㯠false stdout.innerHTML += "null is " + ( null ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "undefined is " + ( undefined ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "object is " + ( new Object() ? "true" : "false" ) + ".<br/>"; // æ°å / 0 ã¯false stdout.innerHTML += "0 is " + ( 0 ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "1 is " + ( 1 ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "-1 is " + ( -1 ? "true" : "false" ) + ".<br/>"; // æåå / 空æåã¯false stdout.innerHTML += " is " + ( "" ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "a is " + ( "a" ? "true" : "false" ) + ".<br/>"; // é å / ã©ã¡ããtrue stdout.innerHTML += "[] is " + ( [] ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "['a'] is " + ( ['a'] ? "true" : "false" ) + ".<br/>"; // ããã·ã¥ / ã©ã¡ããtrue stdout.innerHTML += "{} is " + ( {} ? "true" : "false" ) + ".<br/>"; stdout.innerHTML += "{a:'a'] is " + ( {a:'a'} ? "true" : "false" ) + ".<br/>";
å®è¡çµæã§ãã
null is false. undefined is false. object is true. 0 is false. 1 is true. -1 is true. is false. a is true. [] is true. ['a'] is true. {} is true. {a:'a'] is true.