1. 河豚號(hào) > 生活百科 >

js去掉前后空格trim(去掉所有空格的用法)

1.Promise 用于解決異步編程
/* * 比如說(shuō) ajax 就是一個(gè)異步操作 , 之前的使用的回調(diào)函數(shù)的方式解決異步編程 * * $.ajax({ * url:’abc.com’, * success:function(res){ * * } * }) * * 場(chǎng)景: * 1.先獲取當(dāng)前token是否已經(jīng)失效 * 2.如果沒(méi)有失效,返回當(dāng)前的token的用戶(hù)的基本信息(基本信息包含 uid ) * 3.根據(jù)uid 來(lái)查詢(xún)當(dāng)前用戶(hù)的會(huì)員等級(jí) * 4.再通過(guò)當(dāng)前用戶(hù)的會(huì)員等級(jí),來(lái)查詢(xún)當(dāng)前用戶(hù)的特權(quán)(來(lái)檢測(cè)用戶(hù)是否有權(quán)限來(lái)執(zhí)行某個(gè)操作) * * 案例: * 已知a.txt 地址 ,然后需要根據(jù)a.txt 返回的結(jié)果進(jìn)行下一次的查詢(xún) ,逐一查詢(xún)到最后的結(jié)果d.txt內(nèi)容 * */
//使用jQuery 實(shí)現(xiàn) = > 造成一個(gè) “回調(diào)地獄”

 $.ajax({
        url:"data/a.txt",
        success:function(res){
            console.log('第一次:',res);
            //再發(fā)出下一次請(qǐng)求
            $.ajax({
                url:res,
                success:function(res){
                    console.log('第二次',res);
                    $.ajax({
                        url:res,
                        success:function (res) {
                            console.log('第三次:',res);
                            $.ajax({
                                url:res,
                                success:function (res) {
                                    console.log("第四次:",res);
                                }
                            })
                        }
                    })
                }
            })
        }
    })

2. Promise 用于解決異步編程的一種解決方案, 也可以理解是一個(gè)執(zhí)行異步操作的容器,在容器中封裝好了一套處理異步的流程機(jī)制

* 1.有三種狀態(tài):pending(進(jìn)行中)、fulfilled(已成功)和rejected(已失?。?/p>

* 2.一旦狀態(tài)改變,就不會(huì)再變,任何時(shí)候都可以得到這個(gè)結(jié)果。從pending – > fulfilled (成功) 或者 pending -> 和rejected (失敗) , 每次只能改變一次狀態(tài)

* * 常用方法

* all()

* race()

var promise = new Promise(function(resolve,reject){//創(chuàng)建一個(gè)promise容器 , resolve 一個(gè)用于在處理異步成功時(shí)調(diào)用的函數(shù) , reject 處理異步失敗的時(shí)候調(diào)用的函數(shù) setTimeout(function(){ //通過(guò)延時(shí)定時(shí)器模擬異步 , 2000ms 結(jié)束后就可以調(diào)用成功或者失敗 console.log(‘時(shí)間到了!!!’); resolve(123456); reject(12) },2000); }); //當(dāng)實(shí)例化Promise之后(已經(jīng)執(zhí)行異步操作) , (結(jié)果怎么樣)然后呢? then() 編寫(xiě)需要執(zhí)行的回調(diào)業(yè)務(wù) promise.then(function(res){ console.log(“執(zhí)行成功!”,res); },function(err){ console.log(“執(zhí)行失敗!”,err); });

3.使用promise 異步編程封裝一個(gè)ajax模塊

 //使用promise 異步編程封裝一個(gè)ajax模塊
    function Ajax(url){
        //創(chuàng)建一個(gè)Promise實(shí)例
      return  new Promise(function(resolve,reject){
            var xhr = new XMLHttpRequest();
            //綁定請(qǐng)求過(guò)程狀態(tài)改變事件
            xhr.onreadystatechange = function () {
                    if(xhr.readyState==4){
                        if((xhr.status >= 200 && xhr.status<=304)){
                            resolve(xhr.responseText);
                        }else{
                            reject(xhr.statusText);
                        }
                    }
            }
            //發(fā)起請(qǐng)求
            xhr.open("get",url);
            xhr.send(null);
        });
    }
    //使用
    // all() 可以同時(shí)擁有幾個(gè)異步操作,  如果有一個(gè)失敗 ,則觸發(fā)失敗
    // Promise.all([Ajax('data/a.txt'),Ajax('data/b.txt'),Ajax('data/c3.txt')]).then(function (res) {
    //     console.log("成功:",res);
    // }).catch(function (err) {
    //     console.log("失敗:",err);
    // })

    //race() 競(jìng)速
    Promise.race([Ajax('data/a.txt'),Ajax('data/b.txt'),Ajax('data/c3.txt')]).then(function (res) {
        console.log("成功:",res);
    }).catch(function (err) {
        console.log("失敗:",err);
    })

4.使用promise 異步編程封裝一個(gè)ajax模塊

 function Ajax(url){
        //創(chuàng)建一個(gè)Promise實(shí)例
      return  new Promise(function(resolve,reject){
            var xhr = new XMLHttpRequest();
            //綁定請(qǐng)求過(guò)程狀態(tài)改變事件
            xhr.onreadystatechange = function () {
                    if(xhr.readyState==4){
                        if((xhr.status >= 200 && xhr.status<=304)){
                            resolve(xhr.responseText);
                        }else{
                            reject(xhr.statusText);
                        }
                    }
            }
            //發(fā)起請(qǐng)求
            xhr.open("get",url);
            xhr.send(null);
        });
    }
    //使用
    Ajax("data/a.txt")
      .then(function (res) {
           console.log("第一次成功:",res);
           //調(diào)用下一次
            return Ajax(res);
    }).then(function (res) {
            console.log("第二次成功:",res);
              return Ajax(res);
    }) .then(function (res) {
        console.log("第三次成功:",res);
        //調(diào)用下一次
        return Ajax(res);
    }).then(function (res) {
        console.log("第四次成功:",res);
    }).catch(function () {
       console.log("最后請(qǐng)求失敗!!!");
    })
    // promise().then(()=>{},()=>{})
    // promise().then(()=>{}).catch(()=>{})

5.語(yǔ)法糖 (提供一種代碼更加簡(jiǎn)潔,方便的做法,與之之前的實(shí)現(xiàn)過(guò)程相比,感覺(jué)像是吃了糖一樣美滋滋)

// var a = 10;

// var b = 20;

// var c = 30;

// var d = 40;
//ES6實(shí)現(xiàn) – 數(shù)組形式解構(gòu)賦值

 let [a, b, c, d, e, f] = [10, 20, 30, 40, 50];

        //對(duì)象形式解構(gòu)賦值 , 定義abc , hhh 變量 , 將等號(hào)右邊的foo的值賦值給abc , 等號(hào)右邊的bar的值賦值給hhh
        let { foo: abc, bar: hhh } = { foo: "啊啊啊啊啊", bar: "呵呵呵呵呵" }
        //es6的對(duì)象中有一個(gè)簡(jiǎn)寫(xiě)方式
        var name = "張三";
        var obj = {
            name, // 等于 name:name  ,在對(duì)象中如果屬性名與屬性值的變量名一樣 ,就可以簡(jiǎn)寫(xiě)
            run() {
                console.log('奔跑方法');
            }
        }
        let { foo, bar } = { foo: "啊啊啊啊啊", bar: "呵呵呵呵呵" };
        /*
        使用場(chǎng)景 :
            restFul API 規(guī)范的接口 
            {
                code:200,
                msg:"加載用戶(hù)余額數(shù)據(jù)成功!",
                data:[
                    {
                        id:123123,
                        money:1000
                    },
                    {
                        id:123123,
                        money:1000
                    }
                ]
            }
        */
        var obj = {
            data: {
                res: {
                    code: 200,
                    msg: "加載用戶(hù)余額數(shù)據(jù)成功!",
                    data: [
                        {
                            id: 123123,
                            money: 1000
                        },
                        {
                            id: 123123,
                            money: 1000
                        }
                    ]
                }
            }
        }
        //使用ES6 解構(gòu)賦值快速搞定
        let { code , data , msg} = obj.data.res;
        //需要根據(jù)返回的狀態(tài)碼 ,做出對(duì)應(yīng)的提示內(nèi)容(彈窗) ,將數(shù)據(jù)列表輸出在控制臺(tái)    
        // if (obj.data.res.code == 200) {
        //     alert(obj.data.res.msg);
        //     console.log(obj.data.res.data);
        // } 
         if (code == 200) {
            alert(msg);
            console.log(data);
        }     

6.字符串:

* 1.新增一些常用方法:

* includes() 用于檢測(cè)字符串中是否包含指定字符. , 返回布爾值

* startsWith() 用于檢測(cè)字符的開(kāi)頭是否包含指定字符 , 返回布爾值

* endsWith() 用于檢測(cè)字符串的結(jié)尾是否包含指定字符 ,返回布爾值

* padStart(length,str) 對(duì)字符串進(jìn)行l(wèi)ength長(zhǎng)度的前補(bǔ)位 ,不足使用str去補(bǔ)

padEnd(length,str) 對(duì)字符串進(jìn)行l(wèi)ength長(zhǎng)度的后補(bǔ)位 ,不足使用str去補(bǔ)

repeat(times) 對(duì)字符串進(jìn)行times 次重復(fù)
trimStart() 去除字符串開(kāi)頭位置的空格

trimEnd() 去除字符串結(jié)束位置的空格

trim() 去除字符串前后的空格 * * * 2.模板字符串 * * */

var s = '10000';
    console.log(s.padStart(8,0));

    var studentName = '張三';
    var bookName = "<<且聽(tīng)風(fēng)吟>>";
    // document.write('<h3>'+studentName+"正在讀一本書(shū),書(shū)名為"+bookName+'</h3>');
    //使用ES6的模板字符串
    document.write(`<h3>${studentName}正在讀一本書(shū),書(shū)名為${bookName}</h3>`);

7.數(shù)據(jù)結(jié)構(gòu)?? : 數(shù)據(jù)結(jié)構(gòu)是計(jì)算機(jī)存儲(chǔ)、組織數(shù)據(jù)的方式。數(shù)據(jù)結(jié)構(gòu)是指相互之間存在一種或多種特定關(guān)系的數(shù)據(jù)元素的集合
//數(shù)據(jù)類(lèi)型:存儲(chǔ)的數(shù)據(jù)類(lèi)型(boolean , string , undefined , null , number ,object , smybol) //Set() 集合

 var set = new Set([1,2,3,4,5,5,3]);
        console.log(set);
        //1.不能直接使用下標(biāo)訪(fǎng)問(wèn) ,一般通過(guò)一些遍歷方式得到值
        //2.唯一性 : 在集合的內(nèi)部 ,一個(gè)相同的值 只允許出現(xiàn)一次 (可以用來(lái)實(shí)現(xiàn)數(shù)組的去重)
        var arr = [10,20,30,40,50,50,40,30,20,10];
        var arr2 = new Set(arr);
        console.log(arr2); 
        arr = Array.from(arr2); //將一些集合類(lèi)型數(shù)據(jù)轉(zhuǎn)換成數(shù)組

        //Map() 映射 , 為了解決傳統(tǒng)對(duì)象的鍵值對(duì)關(guān)系中, 鍵名只能以字符串?dāng)?shù)據(jù)類(lèi)型的問(wèn)題
        var obj = {
            20:'這是一個(gè)數(shù)字',
            true:"這是一個(gè)true"
            // [0,1,2]:'sssaadasad'
        }

8.proxy (代理) :在目標(biāo)對(duì)象之前架設(shè)一層“攔截”,外界對(duì)該對(duì)象的訪(fǎng)問(wèn),都必須先通過(guò)這層攔截,因此提供了一種機(jī)制,可以對(duì)外界的訪(fǎng)問(wèn)進(jìn)行過(guò)濾和改寫(xiě)

  var man = {
            age: 8,
            state: '兒童',
            sex: '女',
            name: "張三"
        }
        //  man.age = -2500; //這樣設(shè)置無(wú)法對(duì)數(shù)據(jù)可靠性,安全性做出處理 ,很容易造成數(shù)據(jù)的混亂
        //攔截處理 : get(在獲取屬性時(shí)會(huì)自動(dòng)觸發(fā))  / set (在設(shè)置屬性時(shí)會(huì)自動(dòng)觸發(fā)) , 在這種攔截機(jī)制中做出需要攔截的操作
        var hanlder = {
            set: function (target, key, value) {
                console.log('正在準(zhǔn)備設(shè)置對(duì)象的屬性...',target, key, value);
                if(key == "age"){
                    if(value>=0 && value<=120){
                        target.age = value;
                        if(value>=0 && value<=12){ //實(shí)現(xiàn)在每次修改年齡的時(shí)候 ,根據(jù)修改年齡的數(shù)值決定對(duì)象屬性state的狀態(tài) ,此處就與age屬性實(shí)現(xiàn)了數(shù)據(jù)的綁定,而不需要在每次設(shè)置age屬性的時(shí)候,都要去寫(xiě)一遍判斷邏輯和操作state
                            target.state="兒童"
                        }else if(value>=13 && value <18){
                            target.state = "少年";
                        }else if(value>=19 && value <30){
                            target.state = "青年";
                        }else{
                            target.state = "老年人";
                        }
                    }else{
                        throw new Error('年齡輸入不合法!!');
                    }
                }
            },
            get: function (target, key) {
                // console.log('此處應(yīng)該是獲取代理目標(biāo)對(duì)象屬性的攔截操作...',target,key);
                switch (key) {
                    case "age":
                        if (target.sex == '女') {
                            return '女孩子的年齡一般不能問(wèn)的!!';
                        } else {
                            return target.age;
                        }
                    break;
                    default:
                        return target[key];    
                }
                // return '數(shù)據(jù)保密!';
            }
        }
        //實(shí)例化一個(gè)proxy , 其實(shí)就是對(duì)外提供的一個(gè)操作代理對(duì)象(操作時(shí)修改的就是prxoy對(duì)象,但是它會(huì)將數(shù)據(jù)再修改到目標(biāo)對(duì)象上)
        var proxy = new Proxy(man, hanlder);
        console.log('年齡為:', proxy.age); //此時(shí)會(huì)觸發(fā)proxy中的get ,因?yàn)樵讷@取age屬性
        proxy.age = 30;

9.async 函數(shù) ,異步函數(shù) : 目的就將異步操作變成同步操作的方式編寫(xiě)
/** 使用關(guān)鍵字 async 聲明一個(gè)異步函數(shù) , 在調(diào)用異步函數(shù)的之前使用await關(guān)鍵配合使用,來(lái)聲明當(dāng)前執(zhí)行的異步需要等待 ,等await關(guān)鍵字中的函數(shù)執(zhí)行完之后 ,才會(huì)執(zhí)行后邊的代碼 */

 async function timeout(time) {
            return new Promise((resolve, reject) => {
                setTimeout(() => { //模擬一個(gè)異步操作,比如說(shuō)是一次ajax交互
                    resolve(123);
                }, time)
            })
        }
        async function hello(title, time) {
            let s = null;
            await timeout(time).then((res) => {
                // console.log(res);
                s = res;
            });
            console.log(title + s);
        }
        hello("教育改變生活!!!!", 5000);
 
 
 

本文由網(wǎng)上采集發(fā)布,不代表我們立場(chǎng),轉(zhuǎn)載聯(lián)系作者并注明出處:http://m.zltfw.cn/shbk/39381.html

聯(lián)系我們

在線(xiàn)咨詢(xún):點(diǎn)擊這里給我發(fā)消息

微信號(hào):15705946153

工作日:9:30-18:30,節(jié)假日休息