Home >Web Front-end >JS Tutorial >How to detect original values in web development
This time I will show you how to detect the original value in web development, and what are the precautions for detecting the original value in web development. The following is a practical case, let's take a look.
There are 5 primitive types in JS: string, number, Boolean value, null and undefined. If you want a value to be a string, number, boolean, or undefined, your best option is to use the typeof operator. The typeof operator returns a string representing the type of the value.
For strings, typeof returns "string".
For numbers, typeof returns "number".
For Boolean values, typeof returns "boolean".
For undefined, typeof returns "undefined".
The usage of typeof is as follows:
// 推荐使用,这种用法让`typeof`看起来像运算符typeof variable// 不推荐使用,因为它让`typeof`看起来像函数调用typeof(variable)
It is very safe to use typeof to detect the above four primitive value types.
The unique thing about the typeof operator is that it will not throw an error when used on an undeclared variable. Undefined variables and variables with undefined values will return "undefined" through typeof.
The last primitive value, null, generally should not be used to detect statements. As mentioned above, simply comparing to null usually does not contain enough information to determine whether the value is of a legal type. But there is an exception. If the expected value is really null, you can compare it directly with null. At this time, === or !== should be used to compare with null, for example:
// 如果你需要检测null,则使用这种方法var element = document.getElementById('my-div');if (element !== null) { element.className = 'found'; }
If the DOM element does not exist, the value obtained through document.getElementById() is null. This method either returns a node or null. Since null is a predictable output at this time, you can use !== to detect the return result.
Running typeof null returns "object", which is an inefficient way to determine null. If you need to detect null, use the identity operator (===) or the non-identity operator (!==) directly.
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:
Use JS to implement encryption and decryption operations
How to make a node.js interface
The above is the detailed content of How to detect original values in web development. For more information, please follow other related articles on the PHP Chinese website!