js cookei 日期轉換 隨機ID 隨機顏色 數組位置打亂 工作開發提升效率

==============》常用JS API

1. 數組操作
  split()     //把字符串以特殊條件轉完數組   (例如:"a,b,c,1,4,d" split(',')  =>    [a,b,c,1,4,d])
  join()     //把數組按照特定的格式轉爲 =》 字符串 和上面方法相反

2.字符串-json
JSON.stringify(Object)  //json轉爲字符串
JSON.parse(String)   //字符串轉JSON
replace(/\s+/g,"") 去掉所有空格

==============》 功能需求篇  自定義封裝函數
1.-----打亂數組 '貪心算法/洗牌算法'
arr = [1,2,3,4,5,6,7...]
newArr = arr.slice().sort( () => Math.random() - 0.5)

2.-----隨機取色
var color = '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6,'0');

3.-----生成隨機數ID
var id = Math.random().toString(36).substring(2);

4、-----日期格式化
DateFormatDate(date){
this.year=date.getFullYear();
    this.month=date.getMonth()+1;
    this.day=date.getDate();
    this.hours=date.getHours();
    this.minute=date.getMinutes();
    this.second=date.getSeconds();
    this.week=date.getDay();
    return this.year+"年"+this.month+"月"+this.day+"日   "+this.hours+":"+this.minute+":"+this.second+" 星期"+this.week;
}
5、-----cookei 操作
cookieService = {
    set:function(key,val,time){
        let date= new Date(); //獲取當前時間
        let expiresDays= time*24*3600*1000;  //將date設置爲n天以後的時間
        date.setTime(date.getTime()+expiresDays); //格式化爲cookie識別的時間
        document.cookie=key + "=" + escape(val) +";expires="+date.toUTCString();  //設置cookie
    },
    get:function(key){
        /*獲取cookie參數*/
        let getCookie = document.cookie.replace(/[ ]/g,"");  //獲取cookie,並且將獲得的cookie格式化,去掉空格字符
        let arrCookie = getCookie.split(";");  //將獲得的cookie以"分號"爲標識 將cookie保存到arrCookie的數組中
        let tips;  //聲明變量tips
        for(let i=0;i<arrCookie.length;i++){   //使用for循環查找cookie中的tips變量
            let arr=arrCookie[i].split("=");   //將單條cookie用"等號"爲標識,將單條cookie保存爲arr數組
            if(key===arr[0]){  //匹配變量名稱,其中arr[0]是指的cookie名稱,如果該條變量爲tips則執行判斷語句中的賦值操作
                tips=arr[1];   //將cookie的值賦給變量tips
                break;   //終止for循環遍歷
            }
        }
        return unescape(tips);
    }
};

6.-----判斷字符串變量是否爲空
function empty(taraget){
  if(!target || typeof(target) !== 'string' ) return false;
  return !(target.trim());
}
7.-----小數保留幾位數
//會向上 
1. toFiex(幾位數)
//不四捨五入
1. Math.floor(15.7784514000 * 100) / 100   // 輸出結果爲 15.77
2. Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))   // 輸出結果爲 15.77,不能用於整數如 10 必須寫爲10.0000

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章