JavaScript checks original values, reference values, attributes, and javascript

Source: Internet
Author: User
Tags type null hasownproperty

JavaScript checks original values, reference values, attributes, and javascript

In JavaScript, we often see code like this: the comparison between variables and null (this usage is very problematic) is used to determine whether a variable is given a reasonable value. For example:

Var Controller = {process: function (items) {if (items! = Null) {// difficult to write items. sort (); items. forEach (function (item) {// execute some logic });}}}

In this Code, the process () method obviously wants items to be an array, because we can see that items has sort () and forEach (). The intention of this code is very obvious: if the items parameter is not a group number, stop the next operation. The problem with this writing is that the comparison with null cannot really avoid errors. The value of items can be 1, a string, or even any object. These values are not equal to null, which leads to errors once the process () method is executed to sort.

Comparison with null alone does not provide enough information to determine whether subsequent code execution is truly safe. Fortunately, JavaScript provides us with many methods to detect the true values of variables.

Check Original Value

There are five primitive types (also called simple data types) in JavaScript: String, Number, Boolean, Undefined, and Null. If you want a value to be String, Number, Boolean, or Undefined, the optimal choice is to use the typeof operator, which returns a String that represents the type.

For strings, typeof returns "string ".

For numbers, typeof returns "number ".

For boolean values, typeof returns "boolean ".

For undefined, typeof returns "undefined ".

The basic syntax of typeof is: typeof variable. You can also use typeof (variable). Although this is a legal JavaScript syntax, this usage makes typeof look like a function rather than an operator. In view of this, we recommend that you write without parentheses.

It is safe to use typeof to detect these four primitive types. Let's look at the following examples.

// Detect "String" if (typeof name = "string") {anotherName = name. substring (3);} // detect "Number" if (typeof count = "number") {updateCount (count );} // detect "Boolean" if (typeof found = "boolean" & found) {message ("Found! ");} // Detect" Undefined "if (typeof MyApp =" undefined ") {MyApp = {// other code };}

The typeof operator is unique in that it is used for an undeclared variable and no error is reported. If undefined variables and values are undefined, "undefined" is returned through typeof ".

The last Original Type null will return "object" Through typeof, which looks weird and is considered a serious bug of the Standard Specification, therefore, we should avoid using typeof to detect the null type during programming.

console.log(typeof null); // "object"

Compared with null, null usually does not contain enough information to determine whether the value type is valid. Therefore, null is generally not used to detect statements.

However, there is an exception. If the expected value is true null, you can directly compare it with null. For example:

// If You Need To detect null, use this method 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, you can use the constant equals operator ==or non-constant equals Operator! = To detect the returned results.

In addition to the string, number, boolean, undefined, and object mentioned above, the return value of the typeof operator also has a function. Technically speaking, functions are also objects in JavaScript, not a data type. However, functions do have some special attributes. Therefore, it is necessary to distinguish functions from other objects by using the typeof operator. This feature will be used in subsequent detection functions.

Check reference value

In JavaScript, all values except the original values are reference values (also called objects). Common reference types include Object, Array, Date, and RegExp. These reference types are all built-in JavaScript objects. The typeof operator returns "object" when judging all the reference types ".

console.log(typeof {}); // "object"console.log(typeof []); // "object"console.log(typeof new Date()); // "object"console.log(typeof new RegExp()); // "object"

The best way to detect a reference value type is to use the instanceof operator. The basic syntax of instanceof is:

Value instanceof constructor // check Date if (value instanceof Date) {console. log (value. getFullYear);} // checks Errorif (value instanceof Error) {throw value;} // checks the regular expression if (value instanceof RegExp) {if (value. test (anotherValue) {console. log ("Matches ");}}

An interesting feature of instanceof is that it not only detects the constructor that constructs this object, but also detects the prototype chain. The prototype chain contains a lot of information, including the inheritance mode used to define objects. For example, by default, each Object is inherited from an Object, so the value instanceof Object of each Object returns true. For example:

Var now = new Date (); console. log (now instanceof Object); // tureconsole. log (now instanceof Date); // The tureinstanceof operator can also detect custom types, such as: function Person (name) {this. name = name;} var me = new Person ("Nicolas"); console. log (me instanceof Object); // tureconsole. log (me instanceof Person); // ture

The Person type is created in this sample code. The variable me is an instance of Person, so me instanceof Person is true. As mentioned above, all objects are considered as Object instances, so me instanceof Object is also true.

When detecting built-in and custom types in JavaScript, the best practice is to use the instanceof operator, which is the only method.

However, there is A severe restriction. Assume that both frames in the browser have the constructor Person, and the Person instance frameAPersonInstance in frame A is transferred to frame B, the following results will be returned:

Console. log (frameAPersonInstance instanceof frameAPerson) // ture
Console. log (frameAPersonInstance instanceof frameBPerson) // false
Although the definitions of two persons are identical, they are considered to be of different types in Different frames. There are two very important built-in types that also have this problem: Array and Function, so the instanceof is not used for detection.

Detection Function

Technically speaking, functions in JavaScript are reference types, and Function constructor also exists. Each Function is its instance, for example:

Function myFunc () {}// poor syntax console. log (myFunc instanceof Function); // true

However, this method cannot be used across frames because each frame has its own Function constructor. Fortunately, the typeof operator can also be used as a function and "Function" is returned ".

Function myFunc () {}// a good way to write console. log (typeof myFunc = "function"); // true

The best way to detect a function is to use typeof because it can be used across frames.

Using typeof to detect a function has a limit. In IE 8 and earlier versions, typeof is used to detect that all functions in DOM nodes return "object" instead of "function ". For example:

// IE8 and earlier versions of IEconsole. log (typeof document. createElement); // "object" console. log (typeof document. getElementById); // "object" console. log (typeof document. getElementByTagName); // "object"

This strange phenomenon occurs because browsers have different implementations of DOM. In short, these earlier versions of IE did not implement DOM as a built-in JavaScript method, resulting in the built-in typeof operator to recognize these functions as objects. DOM is clearly defined. If an object member exists, it means it is a method. Developers often use the in operator to detect DOM methods. For example:

// Check the DOM method if ("querySelectorAll" in document) {var images = document. querySelectorAll ("img ");}

This code checks whether querySelectorAll is defined in document. If yes, this method is used. Although it is not the best method, it is the safest way to check whether the DOM method exists in IE 8 or earlier browsers. In all other cases, the typeof operator is the best choice for detecting JavaScript Functions.

Detection array

One of the oldest cross-origin problems in JavaScript is to transfer arrays back and forth between frames. Developers soon discovered that instanceof Array could not return correct results in this scenario. As mentioned above, each frame has its own Array constructor, so instances in one frame are not recognized in another frame.

There have been many researches on how to detect array types in JavaScript. Finally, Kangax provides an elegant solution:

function isArray(value) {return === "[object Array]";}

Kangax finds that the built-in toString () method that calls a value will return standard string results in all browsers. For an Array, the returned string is "[object Array]", and you do not need to consider which frame the Array instance is constructed. This method is often useful when identifying built-in objects, but do not use this method for custom objects.

ECMAScript5 formally introduces Array. isArray () to JavaScript. The unique purpose is to accurately check whether a value is an array. Like the Kangax function, Array. isArray () can also detect cross-frame passed values. Therefore, many JavaScript Class Libraries currently implement this method similarly.

function isArray(value) {if (typeof Array.isArray === "function") {return Array.isArray(value);} else {return === "[object Array]";}}

IE 9 +, FireFox 4 +, Safari 5 +, Opera 10.5 +, and Chrome all implement the Array. isArray () method.

Check attributes

Another scenario that uses null (and undefined) is to check whether an attribute exists in an object. For example:

// Bad writing method: Check the false value if (object [propertyName]) {// some code} // bad writing method: Compare with null if (object [propertyName]! = Null) {// some code} // poor Syntax: Compared with undefined, if (object [propertyName]! = Undefined) {// some code}

In the above Code, each judgment actually checks the attribute value by the given name, rather than determining whether the attribute referred to by the given name exists. In the first judgment, when the attribute value is a false value, the result will be wrong, such as: 0, "(empty string), false, null, and undefined. After all, these are the valid values of the attribute.

The best way to determine whether an attribute exists is to use the in operator. The in operator simply determines whether an attribute exists and does not read the attribute value. If the attribute of an instance object exists or inherits the prototype of the object, the in operator returns true. For example:

Var object = {count: 0, related: null}; // a good way to write if ("count" in object) {// The code here will be executed} // a bad way to write: check if (object ["count"]) {// The code here will not be executed} // a good way to write if ("related" in object) {// The code here will execute} // a bad way to check if it is an if (object ["related"]! = Null) {// The code here will not be executed}

If you only want to check whether a property of the instance object exists, use the hasOwnProperty () method. All JavaScript objects inherited from the Object have this method. If this property exists in the instance, true is returned (if this property only exists in the prototype, false is returned ). Note that in IE 8 and earlier versions, DOM objects do not inherit from objects and therefore do not include this method. That is to say, you should check whether the hasOwnProperty () method of the DOM object exists before calling it.

// For all non-DOM objects, this is a good way to write if (object. hasOwnProperty ("related") {// execute the code here} // If you are not sure whether it is a DOM object, then write if ("hasOwnProperty" in object & object. hasOwnProperty ("related") {// execute the code here}

In the case of IE 8 or earlier versions, I prefer to use the in operator when determining whether the attributes of the Instance Object exist, hasOwnProperty () is used only when instance attributes need to be determined ().

Whenever you need to check the existence of attributes, use the in operator or hasOwnProperty (). This avoids many bugs.

The above section describes how to use JavaScript to check the original values, reference values, and attributes. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.