Don*_*n P 51 javascript typeof
typeof (myVariable)比较之间有什么区别typeof myVariable吗?
两者都有效,但是来自PHP,我不明白为什么这个函数可以使用括号.
Hal*_*oum 67
该typeof关键字表示运营商的Javascript节目.
规范中typeof运算符的正确定义是:
typeof[(]expression[)] ;
Run Code Online (Sandbox Code Playgroud)
这就是使用typeofas typeof(expression)或者背后的原因typeof expression.
来到为什么它已被实现为这样可能是为了让开发人员在处理他的代码水平能见度.因此,可以使用typeof使用干净的条件语句:
if ( typeof myVar === 'undefined' )
// ...
;
Run Code Online (Sandbox Code Playgroud)
或者使用分组运算符定义更复杂的表达式:
const isTrue = (typeof (myVar = anotherVar) !== 'undefined') && (myVar === true);
Run Code Online (Sandbox Code Playgroud)
编辑:
在某些情况下,对typeof运算符使用括号会使编写的代码不易产生歧义.
以下面的表达式为例,其中typeof运算符没有括号.会typeof返回空字符串文字和数字之间连接结果的类型,还是字符串文字的类型?
typeof "" + 42
Run Code Online (Sandbox Code Playgroud)
综观上述操作者的定义和运算符的优先级typeof和+,看来前面的表达式是等效于:
typeof("") + 42 // Returns the string `string42`
Run Code Online (Sandbox Code Playgroud)
在这种情况下,使用括号typeof可以更清晰地表达您要表达的内容:
typeof("" + 42) // Returns the string `string`
Run Code Online (Sandbox Code Playgroud)