首页 > 语言 > JavaScript > 正文

Javascript中常用的检测方法小结

2024-05-06 15:08:47
字体:
来源:转载
供稿:网友

一、数组检测

1.使用ARRAY.ISARRAY()

Array.isArray(obj)

例如:

Array.isArray([]) //trueArray.isArray({}) //false

兼容性:

CHROME FIREFOX IE OPERA SAFARI
5 4.0(2.0) 9 10.5 5

可以使用以下方式,先检测是否支持Array.isArray

if(Array.isArray){  return Array.isArray(obj);}

2. 使用INSTANCEOF

arr instanceof Array

例如:

var arr=[];console.log(arr instanceof Array); //true

3. 使用OBJECT.PROTOTYPE.TOSTRING方法

if( Object.prototype.toString.call(arr) === '[object Array]' ) {  console.log("yes");}

4.使用CONSTRUCTOR的方法

function isArray(obj){  return !!obj && Array === obj.constructor;}

二、类型检测

typeof操作符检测给定变量的数据类型

typeof operand //operand 是一个表达式,表示对象或原始值

以下是一些常见类型的返回结果,值得注意的是null返回的是object,其实对于引用类型的判断都为object。

 TYPE   RESULT
 Undefined “undefined”
 Null “object” (see below)
 Boolean “boolean”
Number “number”
String “string”
Symbol (new in ECMAScript 2015)  “symbol”
Host object (provided by the JS environment) Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) “function”
Any other object “object”

三、对象类型检测

1. INSTANCEOF

用来检测 constructor.prototype是否存在于object 的原型链上

使用方式:

object instanceof constructor

举个例子:

function A(){};var a=new A();a instanceof A //truea instanceof Object //truea.prototype instanceof Object //true            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选