JavaScript- essay writing maintainable (six)

Compare avoid empty

If(item !== null){

   item.sort();

Item.forEach(function(item){

// execute code

}

}

}

Above judgment item is expected array type, but if the item is numeric or string of words will enter the execution condition if, and only be null comparison is not really safe

 

Detecting original value

If the desired value is a string, number, Boolean, or undefined, the best option is to use typeof operator, typeof returns a value indicating the type of string

String, typeof returns the string

Digital, typeof Returns number

Boolean value, typeof returns a boolean

undefined,typeof返回undefined

Syntax: ①, typeof variable ②, typeof (variable)

It is undefined undefined variables and the return undefined variables typeof

typeof null is returned object

Null detection is generally not used unless really desired null value, should be compared with the use of congruent null

 

Detection reference value

Reference value has become the object of several reference types: object, array, date, error

Typeof reference object using object detection return values ​​are

The best type of detection method is to use a reference value instanceof operator

The basic syntax: value instanceof constructor (reference types)

Instanceof detect not only the object constructor, the prototype chain is also detected, by default, every object inherits from the Object, each object value instanceof Object returns a true

And generally do not need to use an array function instanceof

The best method of detection is to use the function to return function typeof

The oldest method of detecting array is identified canard type, if there is sort method by detecting the target variable

More elegant solution: Object.prototype.toString.call (value) === "[object Array]"

 

Detection property

When detecting a property exists in the object

// bad writing

If(object[propertyName]){

// some code

}

If(object[propertyName] != null){

// some code

}

If(object[propertyName] != undefined){

// some code

}

Actually written over by checking the value of a given attribute name, a value of 0, an empty string, determined that false, null and undefined error occurs.

The best way to determine whether there is an attribute used in operator

var object = {

count:0,

related:null

}

// good writing

if(“count” in object){

// code execution

}

If the detection point of the object's instance attributes are present, use hasOwnProperty () method returns true if this attribute is present instance, if the property is only present in the prototype false if

Guess you like

Origin www.cnblogs.com/wyongz/p/11325928.html