Home > Web Front-end > JS Tutorial > How to get pure undefined in JavaScript_javascript tips

How to get pure undefined in JavaScript_javascript tips

WBOY
Release: 2016-05-16 15:12:08
Original
1605 people have browsed it

1. Why should we get undefined?

Because undefined is not a reserved word in JavaScript, it can be assigned a value by the user as a variable. If we need to use undefined to detect a variable later, the detected value will be inaccurate;

Give me an example:

var undefined=10;
function sum(a,b){
 if(a===undefined||b===undefined){
  console.log("参数不正确");
 }18101130357
 return a+b;
}
Copy after login

sum(10,10)->Originally correct parameters, the console output is indeed "parameter error";

At this time, in order to be compatible with all browsers, we need to obtain a pure undefinde

2. How to get pure undefined?

1) void (0):

In the ECMAScript 262 specification, it is described as follows:

The void Operator
The production UnaryExpression : void UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Call GetValue(expr).
Return undefined.
Copy after login

In short, just remember that no matter what the expression after void is, the void operator will return undefined

2) Pass in a formal parameter for assignment

[Case]

function(_undefined){
//函数体中不给_undefined赋值,形参_undefined的值就是undefined,在这个函数用就可以使用_undefined了
}
Copy after login

3) Unassigned variable

For example: var num //The principle is the same as 2)

Don’t be bored with familiar things, make a little progress every day; don’t be afraid of unfamiliar things, learn a little every day;

PS: js determines undefined type

 if (reValue== undefined){
 alert("undefined");
 }
 发现判断不出来,最后查了下资料要用typeof
方法:
if (typeof(reValue) == "undefined") { 
 alert("undefined"); 
}
Copy after login

typeof returns a string, there are six possibilities: "number", "string", "boolean", "object", "function", "undefined"

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template