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

本文介绍JavaScript中获取某个月的天数、变量类型判断、字符串前后空格去除及数组操作等基础技巧,并提供了jQuery中trim()方法的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

 

转载于:https://www.cnblogs.com/wangez/p/5550411.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值