1. 程式人生 > >JS方法擴充套件,擴充套件ing

JS方法擴充套件,擴充套件ing

一、簡單地仿PHP date()方法,返回特定格式的日期和時間。

function date(format = 'Y-m-d H:i:s',timestamp = false){
	let now = new Date();
	if(timestamp){
		if(timestamp.toString().length === 13){
			now.setTime(timestamp);	
		}else{
			console.log('時間戳應該為毫秒');
			return false;
		}
	}
	let str = '',i = 0,w;
	while(w = format.charAt(i++)){
		switch(w){
			case 'Y':
				str += now.getFullYear();
				break;
			case 'm':
				str += pad0(now.getMonth() + 1);
				break;
			case 'd':
				str += pad0(now.getDate());
				break;
			case 'H':
				str += pad0(now.getHours());
				break;
			case 'i':
				str += pad0(now.getMinutes());
				break;
			case 's':
				str += pad0(now.getSeconds());
				break;
			default:
				str += w;
		}
	}
	return str;
}
function pad0(value){
    return value > 9 ? value : '0' + value;
}

二、刪除陣列中指定的值

Array.prototype.deleteValue = function(value){
    let index = this.indexOf(value);
    return index > -1 ? this.splice(index,1) : false;
}