前端开发中的一些js小技巧

1、获取某个月的天数

1 function getDate (year, month) {
2     return new Date(year, month + 1, 0).getDate();
3 }

2、获取变量类型

1 function getType (e) {
2     return Object.prototype.toString.apply(e);
3 }
1 getType('aa');            //[object String]
2 getType(11);             //[object Number]
3 getType(undefined);  //[object Undefined]
4 getType([]);              //[object Array]
5 getType({});             //[object Object]
6 getType(null);           //[object Null]

 简单处理下

function getType (e) {
    return Object.prototype.toString.apply(e).replace(/\[object\s|\]/g, '');
}

jquery中方法

  var class2type = {};

  var toString = class2type.toString;

jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );

通过class2type[ toString.call( obj ) ]判断变量obj类型。

 3、去掉字符串前后的空格

jquery的trim()方法源码如下

// Used for trimming whitespace 
trimLeft = /^\s+/, 
trimRight = /\s+$/, 

// Use native String.trim function wherever possible 
trim: trim ? 
function( text ) { 
return text == null ? 
"" : 
trim.call( text ); 
} : 

// Otherwise use our own trimming functionality 
function( text ) { 
return text == null ? 
"" : 
text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); 
},

修改下正则

function myTrim (str) {
    var exp = /^\s+|\s+$/g;
    return str == null ?
    "" :
    str.toString().replace( exp, "");
}

 4、数组操作

var old = [],
      new1,
      new2;
new1 = old;
new2 = old.slice(0);
old.push(1);
console.log(old.length);
console.log(new1.length);
console.log(new2.length);

 

posted @ 2016-06-01 17:33  王恩智  阅读(320)  评论(0)    收藏  举报