This article is about popularizing basic knowledge, js determines data types, etc. We all know that there is is_array() function in php, but not in js. When we judge whether the data type is an array, we usually write a function to make the judgment just to be on the safe side. Today, I will popularize some basic data type judgment methods. I hope it will be helpful to everyone.
Typeof is often used to determine whether a global variable exists. If a global variable is defined on a page. If you make the following judgment:
//haorooms是全局变量if(haorooms!=undefined){}//js会报错,说"Uncaught ReferenceError: haorooms is not defined"
The solution is for us to write as follows:
if(typeof haorooms!=undefined){ }
After using typeof, there will be no error! This is one of the applications of typeof!
In addition, typeof can also determine the data type! As follows:
var haorooms="string"; console.log(haorooms); //stringvar haorooms=1; console.log(haorooms); //numbervar haorooms=false; console.log(haorooms); //booleanvar haorooms; console.log(typeof haorooms); //undfinedvar haorooms= null; console.log(typeof haorooms); //objectvar haorooms = document; console.log(typeof haorooms); //objectvar haorooms = []; console.log(haorooms); //objectvar haorooms = function(){}; console.log(typeof haorooms) //function 除了可以判断数据类型还可以判断function类型
Obviously, for typeof, in addition to the first four types, null, object, and array return all object types;
can be used It determines whether it is an array.
var haorooms=[];console.log(haorooms instanceof Array) //返回true
constructor is the constructor corresponding to the returned object.
Methods to determine various data types:
console.log([].constructor == Array);console.log({}.constructor == Object);console.log("string".constructor == String);console.log((123).constructor == Number);console.log(true.constructor == Boolean);function employee(name,job,born){ this.name=name; this.job=job; this.born=born; }var haorooms=new employee("Bill Gates","Engineer",1985); console.log(haorooms.constructor); //输出function employee(name, jobtitle, born){this.name = name; this.jobtitle = job; this.born = born;}
By outputting haorooms.constructor, you can see that constructor is the constructor corresponding to the returned object.
The above is the detailed content of How to use js to determine whether it is an array. For more information, please follow other related articles on the PHP Chinese website!