Type Detection
Since JavaScript is a loosely-typed language, it is sometimes necessary to examine a value to determine its type. (This is sometimes necessary in strongly typed languages as well.) JavaScript provides a typeof operator to facilitate this, but typeof has problems.
Object 'object'
Array 'object'
Function 'function'
String 'string'
Number 'number'
Boolean 'boolean'
null 'object'
undefined 'undefined'
typeof [] produces 'object' instead of 'array'. That isn't totally wrong since arrays in JavaScript inherit from objects, but it isn't very useful. typeof null produces 'object' instead of 'null'. That is totally wrong.
We can correct this by defining our own typeOf function, which we can use in place of the defective typeof operator.
Since JavaScript is a loosely-typed language, it is sometimes necessary to examine a value to determine its type. (This is sometimes necessary in strongly typed languages as well.) JavaScript provides a typeof operator to facilitate this, but typeof has problems.
Object 'object'
Array 'object'
Function 'function'
String 'string'
Number 'number'
Boolean 'boolean'
null 'object'
undefined 'undefined'
typeof [] produces 'object' instead of 'array'. That isn't totally wrong since arrays in JavaScript inherit from objects, but it isn't very useful. typeof null produces 'object' instead of 'null'. That is totally wrong.
We can correct this by defining our own typeOf function, which we can use in place of the defective typeof operator.
JavaScript作为一种弱类型语言,在某些情况下需要检查值来确定其类型。本文探讨了JavaScript中typeof操作符的问题,并提出了一种改进的方法来更准确地判断变量类型。
2791

被折叠的 条评论
为什么被折叠?



