Home >Web Front-end >JS Tutorial >Learn javascript's undefined and null_javascript skills from me

Learn javascript's undefined and null_javascript skills from me

WBOY
WBOYOriginal
2016-05-16 15:31:521399browse

When discussing primitive data types in JavaScript, most people know the basics from String to Number to Boolean. These primitive types are fairly simple and behave like common sense. However, this article will focus more on the unique primitive data types Null and Undefined, and what makes them so similar yet paradoxical.

1. Understand null and undefined

In JavaScript, null is a literal and a keyword in the language, used to represent unrecognized object values. In other words, this is used to mean "no value", but you can decide when to get the expected value.

Although similar, undefined actually represents non-existence of a value, which means you have something missing. Both are completely immutable, have no properties and methods, and their properties cannot be assigned values. In fact, a TypeError will be raised when you try to access or define a property that is null or undefined.

Boolean values ​​represented by no value are false, which means they will evaluate to false in a conditional context, such as an if statement. Use the equality operator (==) to compare these two values ​​with other false values, they are not equal except themselves:

null == 0; // false 
undefined == ""; // false 
null == false; // false 
undefined == false; // false 
null == undefined; // true 

However, and other similarities, null and undefined are not equivalent. Each is a unique member of its own type, undefined is of type Undefined and null is of type Object. Compare these two values ​​using the equality operator (===), which requires that both types and values ​​are equal, as shown below:

null === undefined; //false
typeof null; //"object"
typeof undefined; //"undefined"

The above description: null This is an object, but it is empty. And null is a JavaScript reserved keyword.
In addition, when null participates in numerical operations, its value will be automatically converted to 0. Therefore, the following expression will obtain the correct value after calculation:

123 + null;   //123 
123 * null;   //0 

undefined is a special property of the global object (window), and its value is undefined. But typeof undefined returns 'undefined' .
Although undefined has a special meaning, it is indeed a property, and it is a property of the global object (window). Please look at the code below:

alert('undefined' in window);//输出:true 
var anObj = {}; 
alert('undefined' in anObj); //输出:false 

It can be seen from this that undefined is a property of the window object, but it is not a property of the anObj object.
Note:

  • Although undefined is an attribute with special meaning, it is not a reserved keyword in JavaScript. When undefined participates in any numerical calculation, the result must be NaN. By the way, NaN is another special property of the global object (window), and so is Infinity. None of these special attributes are reserved keywords for JavaScript!
  • When verifying that a value or object is null, you need to use "===" to determine. If you only use "==", you cannot determine whether it is null or undefined.

2. Undefined situation occurs
There are many ways to generate code with an undefined value. It is usually encountered when trying to access a value that does not exist. In this case, in a dynamic and weakly typed language like JavaScript, an undefined value will be returned by default instead of rising to an error.

1. Any variable declared without an initial value will have a default value of undefined:

var foo; // 默认值为 undefined 

2. When trying to access a non-existent object property or array item, an undefined value is returned:

var array = [1, 2, 3]; 
var foo = array.foo; // foo 属性不存在, 返回 undefined 
var item = array[5]; // 数组中没有索引为5的项,返回 undefined 

3. If the return statement of the function is omitted, or the return statement does not take any parameters and returns undefined:

var value = (function(){

})(); // 返回 undefined 
var value1 = (function(){
  return;
})(); // 返回 undefined 

4. When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined

function f(x){
  console.log(x)
}
f(); // undefined

Finally, undefined is a predefined global variable (unlike the null keyword) initialized to the undefined value:

'undefined' in window; // true 

ECMAScript 5中,这个变量是只读的,以前并非如此。

三、null的用例

null的用例是使他与众不同的主要方面,因为不像undefined,null被认为是更有用。这正是为什么typeof操作符作用于null值 时返回“object”。最初的理由是,现在仍然是,通常用作一个空引用一个空对象的预期,就像一个占位符。typeof的这种行为已经被确认为一个错 误,虽然提出了修正,出于后兼容的目的,这一点已经保持不变。

一般来说,如果你需要给一个变量或属性指定一个不变值,将它传递给一个函数,或者从一个函数返回null,null几乎总是最好的选择。简而言之,JavaScript使用undefined并且程序员应该使用null。

null的另一个可行的用例,也被认为是良好的实践是一个显式指定变量为无效(object= null)当一个引用不再是必需的。通过分配null值,有效地清除引用,并假设对象没有引用其他代码,指定垃圾收集,确保回收内存。

四、提高undefined性能

当我们在程序中使用undefined值时,实际上使用的是window对象的undefined属性。 同样,当我们定义一个变量但未赋予其初始值,例如:

var aValue; 

这时,JavaScript在所谓的预编译时会将其初始值设置为对window.undefined属性的引用, 于是,当我们将一个变量或值与undefined比较时,实际上是与window对象的undefined属性比较。这个比较过程中,JavaScript会搜索window对象名叫‘undefined'的属性,然后再比较两个操作数的引用指针是否相同。

由于window对象的属性值是非常多的,在每一次与undefined的比较中,搜索window对象的undefined属性都会花费时 间。在需要频繁与undefined进行比较的函数中,这可能会是一个性能问题点。因此,在这种情况下,我们可以自行定义一个局部的undefined变 量,来加快对undefined的比较速度。例如:

function anyFunc() { 
  var undefined; 
  //自定义局部undefined变量 
  if(x == undefined) 
  //作用域上的引用比较 
  while(y != undefined) 
  //作用域上的引用比较 
}; 

其中,定义undefined局部变量时,其初始值会是对window.undefined属性值的引用。新定义的局部undefined变 量存在与该函数的作用域上。在随后的比较操作中,JavaScript代码的书写方式没有任何的改变,但比较速度却很快。因为作用域上的变量数量会远远少 于window对象的属性,搜索变量的速度会极大提高。

这就是许多前端JS框架为什么常常要自己定义一个局部undefined变量的原因!

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement:
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