Home > Web Front-end > JS Tutorial > How to avoid null comparison in web development

How to avoid null comparison in web development

php中世界最好的语言
Release: 2018-06-04 10:48:55
Original
1640 people have browsed it

This time I will show you how to avoid null comparison in web development, and what are the precautions to avoid null comparison in web development. The following is a practical case, let's take a look.

In JS, we often see this kind of code: comparing a variable with null (this usage is very problematic), used to determine whether the variable has been assigned a reasonable value. For example:

var Controller = {  process: function(items) {    if (items !== null) {
      items.sort();
      items.forEach(function(item){});
    }
  }
};
Copy after login

In this code, the process() method obviously expects items to be an array, because we see that items has sort() and forEach(). The intention of this code is very obvious: if the parameter items is not an array, stop the next operation. The problem with this way of writing is that comparison with null does not really prevent errors from occurring. The value of items can be 1, a string, or even any object. These values ​​are not equal to null, which will cause an error once the process() method is executed to sort().

Merely comparing with null does not provide enough information to judge whether the execution of subsequent code is really safe. Fortunately, JS provides us with a variety of methods to detect the real value of variables.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use JS to pass by reference and pass by value

Use JS to implement encryption and decryption operate

The above is the detailed content of How to avoid null comparison in web development. For more information, please follow other related articles on the PHP Chinese website!

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