为了不死在笔试,为秋招作的准备
分为两个部分,一部分讲方法,一部分判断实例
1.Array.prototype 是数组,Object.prototype是对象,Function.prototype是函数
设要判断的变量为variable,要判断的类型X
一、方法:
- 1.typeof variable === X
- 2.variable instanceof X
- 3.variable.constructor === X
- 4.Object.prototype.toString.call(variable) === X
(1)typeof
判断基本类型和Object时
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
值得注意的examples:
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number';
typeof '1' === 'string';
typeof (typeof 1) === 'string';
typeof [1, 2, 4] === 'object';
//new 开头的都是'object'
typeof new Date() === 'object';
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
typeof class C {} === 'function';
typeof Math.sin === 'function';
//几个特列
typeof undefined === 'undefined';
typeof document.all === 'undefined';
typeof null === 'object';
typeof /regularexpression/ === 'object';
(2)instanceof
功能:Checks the current object and returns true if the object
is of the specified object type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
https://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript
值得注意的examples:
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)
// So what instanceof does is it checks the object to see if it is of the type specified
var c = new Customer();
c instanceof Customer; //Returns true
c instanceof String; //Returns false
(3)variable.constructor === X
>
(4)
1.variable.constructor === Array
2.variable instanceof Array
3.Array.isArray(variable)
4.Object.prototype.toString.call(variable) === ‘[object Array]’;