To determine whether an array has a value:
Array.indexOf(val) > -1 //Existence (defect: first, it is not semantic enough. Its meaning is to find the first occurrence position of parameter value, so it is not intuitive to compare whether it is not equal to - 1. Second, it uses strict equality operator (====) to judge internally, which will lead to the misjudgment of NaN. ) Array.includes(val)
Determine whether a field exists in the object:
obj["key"] != undefined//(defect: if the key is defined, and the value of very 2 is undefined) !("key" in obj) obj.hasOwnProperty("key") typeof item.editFlag === "undefined"
Judge whether it is empty
JavaScript itself does not judge whether a variable is a null value function, because variables may be of string, object, number, boolean and other types, with different types and different judgment methods. Therefore, a function is written in the article to determine whether the JS variable is null. If it is undefined, null, "', NaN, false, 0, [], {}, the null string, all return true, otherwise false
function isEmpty(v) { switch (typeof v) { case 'undefined': return true; case 'string': if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true; break; case 'boolean': if (!v) return true; break; case 'number': if (0 === v || isNaN(v)) return true; break; case 'object': if (null === v || v.length === 0) return true; for (var i in v) { return false; } return true; } return false; }
test
isEmpty() //true isEmpty([]) //true isEmpty({}) //true isEmpty(0) //true isEmpty(Number("abc")) //true isEmpty("") //true isEmpty(" ") //true isEmpty(false) //true isEmpty(null) //true isEmpty(undefined) //true typeof typeof undefined === 'undefined' typeof null === 'object' //Boolean typeof true === 'boolean' //Number typeof 1 === 'number' //String typeof '111' === 'string' //Array typeof ['a','b'] === 'object' //Object typeof {a:1,b:2} === 'object'
Judge array method:
instanceof Array objName.constructor==Array //(defect: creating Array in different iframe s does not share prototype; inheriting Array is also true, such as: b.prototype=new Array) length,splice //Length cannot be enumerated (defect: object.propertyIsEnumerable('length ')) Array.isArray(objName) obj.prototype.toString.call(objName)==='[object Array]'