【JavaScript】Object.prototype.toString.call()进行类型判断
权声明:本文为博主原创文章,未经博主允许不得转载。
- op = Object.prototype,
- ostring = op.toString,
- ...
- function isFunction(it) {
- return ostring.call(it) === '[object Function]';
- }
- function isArray(it) {
- return ostring.call(it) === '[object Array]';
- }
最近在看requireJS的源码时,看到上面一段代码,很是好奇,为啥进行类型判断时使用Object.prototype.toString? 如果是我的话就直接用typeof得了,后来查阅了一些资料:
typeof
- 在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。
ECMA 对Object.prototype.toString的解释
- Object.prototype.toString ( )
- When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2
- var oP = Object.prototype,
- toString = oP.toString;
- console.log(toString.call([123]));//[object Array]
- console.log(toString.call('123'));//[object String]
- console.log(toString.call({a: '123'}));//[object Object]
- console.log(toString.call(/123/));//[object RegExp]
- console.log(toString.call(123));//[object Number]
- console.log(toString.call(undefined));//[object Undefined]
- console.log(toString.call(null));//[object Null]
- //....
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小时 --------*********仅支持24小时制**************
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}; //将指定的毫秒数加到此实例的值上
Date.prototype.addMilliseconds = function (value) {
var millisecond = this.getMilliseconds();
this.setMilliseconds(millisecond + value);
return this;
};
//将指定的秒数加到此实例的值上
Date.prototype.addSeconds = function (value) {
var second = this.getSeconds();
this.setSeconds(second + value);
return this;
};
//将指定的分钟数加到此实例的值上
Date.prototype.addMinutes = function (value) {
var minute = this.addMinutes();
this.setMinutes(minute + value);
return this;
};
//将指定的小时数加到此实例的值上
Date.prototype.addHours = function (value) {
var hour = this.getHours();
this.setHours(hour + value);
return this;
};
//将指定的天数加到此实例的值上
Date.prototype.addDays = function (value) {
var date = this.getDate();
this.setDate(date + value);
return this;
};
//将指定的星期数加到此实例的值上
Date.prototype.addWeeks = function (value) {
return this.addDays(value * 7);
};
//将指定的月份数加到此实例的值上
Date.prototype.addMonths = function (value) {
var month = this.getMonth();
this.setMonth(month + value);
return this;
};
//将指定的年份数加到此实例的值上
Date.prototype.addYears = function (value) {
var year = this.getFullYear();
this.setFullYear(year + value);
return this;
}; /**
* @ngdoc function
* @name sUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) { return typeof value === 'undefined'; } /**
* @ngdoc function
* @name sDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) { return typeof value !== 'undefined'; } /**
* @ngdoc function
* @name sObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
} /**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
} /**
* @ngdoc function
* @name sString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) { return typeof value === 'string'; } /**
* @ngdoc function
* @name sNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) { return typeof value === 'number'; } /**
* @ngdoc function
* @name sDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return Object.prototype.toString.call(value) === '[object Date]';
} /**
* @ngdoc function
* @name sArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/ function isArray(value) {
return Object.prototype.toString.call(value) === '[object Array]';
} /**
* @ngdoc function
* @name sFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) { return typeof value === 'function'; } /**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return Object.prototype.toString.call(value) === '[object RegExp]';
} /**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
} function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
} function isFile(obj) {
return Object.prototype.toString.call(obj) === '[object File]';
} function isFormData(obj) {
return Object.prototype.toString.call(obj) === '[object FormData]';
} function isBlob(obj) {
return Object.prototype.toString.call(obj) === '[object Blob]';
} function isBoolean(value) {
return typeof value === 'boolean';
} function isNullOrEmpty(str) {
if (str && str.length > 0) {
return false;
}
return true;
} function trim(str)
{
return str.replace(/(^\s*)|(\s*$)/g, '');
} function ltrim(str)
{
return str.replace(/^\s*/g,'');
} function rtrim(str)
{
return str.replace(/\s*$/,'');
} function equals(str1, str2)
{
if(str1 == str2)
{
return true;
}
return false;
} function equalsIgnoreCase(str1, str2)
{
if(str1.toUpperCase() == str2.toUpperCase())
{
return true;
}
return false;
} function isChinese(str)
{
var str = str.replace(/(^\s*)|(\s*$)/g,'');
if (!(/^[\u4E00-\uFA29]*$/.test(str)
&& (!/^[\uE7C7-\uE7F3]*$/.test(str))))
{
return false;
}
return true;
} function isEmail(str)
{
if(/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str))
{
return true
}
return false;
} function isImg(str)
{
var objReg = new RegExp("[.]+(jpg|jpeg|swf|gif)$", "gi");
if(objReg.test(str))
{
return true;
}
return false;
} function isInteger(str)
{
if(/^-?\d+$/.test(str))
{
return true;
}
return false;
} function isFloat(str)
{
if(/^(-?\d+)(\.\d+)?$/.test(str))
{
return true;
}
return false;
} function isMobile(str)
{
if(/^1[35]\d{9}/.test(str))
{
return true;
}
return false;
} function isPhone(str)
{
if(/^(0[1-9]\d{1,2}-)\d{7,8}(-\d{1,8})?/.test(str))
{
return true;
}
return false;
} function isIP(str){
var reg = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/;
if(reg.test(str))
{
return true;
}
return false;
} function isDateTimeString(str)
{
var reg = /^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;
if(reg.test(str))
{
return true;
}
return false;
}
【JavaScript】Object.prototype.toString.call()进行类型判断的更多相关文章
- Object.prototype.toString.call()进行类型判断
为什么类型判断用到Object.prototype.toString.call()进行类型判断,而不用typeof()呢? 然后翻了一下资料: Typeof 在使用 ]));/));));//[obj ...
- 使用Object.prototype.toString.call()方法精确判断对象的类型
在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number.string.undefined.boolean.object. 对于null.array.function. ...
- JavaScript:Object.prototype.toString方法的原理
在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法. var arr = []; console.log(Obje ...
- JavaScript:Object.prototype.toString进行数据类型判定
在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法. var arr = []; console.log(Obje ...
- js的深入学习课程Object.prototype.toString.call()
1.通过 Object.prototype.toString.call() 进行类型判断 function isArray(obj) { return Object.prototype.toStrin ...
- JavaScript中toStirng()与Object.prototype.toString.call()方法浅谈
toStirng()与Object.prototype.toString.call()方法浅谈 一.toString()是一个怎样的方法?它是能将某一个值转化为字符串的方法.然而它是如何将一个值从一种 ...
- Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()判断数组的方法的优缺点
1. Object.prototype.toString.call() 每一个继承 Object 的对象都有 toString 方法,如果 toString 方法没有重写的话,会返回 [Object ...
- toStirng()与Object.prototype.toString.call()方法浅谈
一.toString()是一个怎样的方法?它是能将某一个值转化为字符串的方法.然而它是如何将一个值从一种类型转化为字符串类型的呢? 通过下面几个例子,我们便能获得答案: 1.将boolean类型的值转 ...
- Object.prototype.toString.call()方法浅谈
使用Object.prototype上的原生toString()方法判断数据类型,使用方法如下: Object.prototype.toString.call(value) 1.判断基本类型: Obj ...
随机推荐
- position属性absolute与relative(转)
每次要用到Position属性时,总要去搜索下,这两个属性值的区别:今天就直接复制网上的结果,以便以后多看看. Absolute,CSS中的写法是:position:absolute; 他的意思是绝对 ...
- Windows中安装Emacs
首先从http://gnu.org/software/emacs中下载window下的压缩包,然后解压..运行ROOT/bin/addpm.exe进行安装. 将鼠标右键添加Emacs编辑: 1. 打开 ...
- Keil C -WARNING L15: MULTIPLE CALL TO SEGMENT
1.第一种错误信息 ***WARNING L15: MULTIPLE CALL TO SEGMENT SEGMENT: ?PR?_WRITE_GMVLX1_REG?D_GMVLX1 CALLER1: ...
- jQuery中的选择器《思维导图》
学习jQuery的课程中,我对jQuery中的选择器有了更深的认识,它的简洁写法,完美的兼容性,可靠的处理机制,都让我们省了很多事, 下面是我在学习过程中对jQuery选择器写的思维导图(全屏查看:& ...
- UESTC_Big Brother 2015 UESTC Training for Graph Theory<Problem G>
G - Big Brother Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others) ...
- HDU 3634 City Planning (离散化)
City Planning Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Tot ...
- C的|、||、&、&&、异或、~、!运算(转)
位运算 位运算的运算分量只能是整型或字符型数据,位运算把运算对象看作是由二进位组成的位串信息,按位完成指定的运算,得到位串信息的结果. 位运算符有: &(按位与).|(按位或) ...
- Android漫游记(1)---内存映射镜像(memory maps)
Android系统内核基于Linux2.6+内核,因此,其在进程内存管理方面的非常多机制和Linux是非常相像的.首先,让我们来看一个典型的Android进程的内存镜像(App进程和Native本地进 ...
- Maven 工程下 Spring MVC 站点配置 (一)
最近,查找一些具体资料时,虽然会有很多,但是系统的却很少,尤其是对maven 下 spring mvc 站点搭建的配置,总是说的很多但让新手一目了然的步骤却少之又少. 对此闲暇时整理了一下,做了一套较 ...
- 使用react-native做一个简单的应用-03欢迎界面
Android和iOS的欢迎界面是不一样的,在iOS中有一个默认的欢迎界面,而Android则需要自己写.因此我就分开说一下这两个平台的欢迎界面的搭建.下面先看一下实现效果: Android: iOS ...