您的位置:首页 > Web前端 > JavaScript

javascript 公共方法 集合

2016-07-29 09:08 148 查看
数组去重:

Array.prototype.unique1 = function () {
var n = []; //一个新的临时数组
for (var i = 0; i < this.length; i++) //遍历当前数组
{
//如果当前数组的第i已经保存进了临时数组,那么跳过,
//否则把当前项push到临时数组里面
if (n.indexOf(this[i]) == -1) n.push(this[i]);
}
return n;
}

Array.prototype.unique2 = function()
{
var n = {},r=[]; //n为hash表,r为临时数组
for(var i = 0; i < this.length; i++) //遍历当前数组
{
if (!n[this[i]]) //如果hash表中没有当前项
{
n[this[i]] = true; //存入hash表
r.push(this[i]); //把当前数组的当前项push到临时数组里面
}
}
return r;
}

Array.prototype.unique3 = function()
{
var n = [this[0]]; //结果数组
for(var i = 1; i < this.length; i++) //从第二项开始遍历
{
//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
//那么表示第i项是重复的,忽略掉。否则存入结果数组
if (this.indexOf(this[i]) == i) n.push(this[i]);
}
return n;
}


操作获取和设置cookie

//创建cookie
function setCookie(name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += '; expires=' + expires;
}
if (path) {
cookieText += '; expires=' + expires;
}
if (domain) {
cookieText += '; domain=' + domain;
}
if (secure) {
cookieText += '; secure';
}
document.cookie = cookieText;
}

//获取cookie
function getCookie(name) {
var cookieName = encodeURIComponent(name) + '=';
var cookieStart = document.cookie.indexOf(cookieName);
var cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(';', cookieStart);
if (cookieEnd == -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
}

//删除cookie
function unsetCookie(name) {
document.cookie = name + "= ; expires=" + new Date(0);
}


当前日期:

let date = new Date();
let defaultDate;
let year =  date.getFullYear();
let month = date.getMonth() + 1;
let day =  date.getDate();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;

defaultDate =  year + "-" + month + "-" + day;


改变当前日期,如果不选择日期,则用默认日期;如果选择日期,则用选择的日期:(react.js)

/**
* 结束时间
*/
export function setEndTime(endTimes){
return{
type: SET_END_TIME,
data: {endTimes}
}
}

/**
* 开始时间
*/
export function setStartTime(startTimes){
return{
type: SET_START_TIME,
data: {startTimes}
}
}

let stateTwo = getState().iosAndroidState;

startTime = stateTwo.startTimes ? stateTwo.startTimes : defaultDate;
endTime = stateTwo.endTimes ? stateTwo.endTimes : defaultDate;


修改当前时间为北京时间

//获得北京时间
Date.prototype.getBJDate = function () {
//获得当前运行环境时间
var d = new Date(), currentDate = new Date(), tmpHours = currentDate.getHours();
//算得时区
var time_zone = -d.getTimezoneOffset() / 60;
//少于0的是西区 西区应该用时区绝对值加京八区 重新设置时间(西区时间比东区时间早 所以加时区间隔)
if (time_zone < 0) {
time_zone = Math.abs(time_zone) + 8; currentDate.setHours(tmpHours + time_zone);
} else {
//大于0的是东区  东区时间直接跟京八区相减
time_zone -= 8; currentDate.setHours(tmpHours - time_zone);
}
return currentDate;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: