[ES6] 基礎和 anyproxy 中的使用示例

bauul發表於2020-05-25

var,let,const

// var的問題
1. var 宣告的變數往往會越域
2. var可以宣告多次
3. var 會變數提升

// let
1. let 宣告的變數有嚴格區域性作用域
2. let 只能宣告一次
3. let 不存在變數提升
4. let 宣告時需要初始化

// const
1. 宣告後不允許改變

解構表示式

//陣列解構
let arr = [1,2,3];
let a = arr[0];
let b = arr[1];
let c = arr[2];

// 解構寫法
let [a,b,c] = arr;

// 物件解構
const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }
const { name: abc, age, language } = person;

// 宣告物件簡寫
        const age = 23
        const name = "張三"
        const person1 = { age: age, name: name }

        const person2 = { age, name }
        console.log(person2);

字串擴充套件

let str = "hello.vue";
console.log(str.startsWith("hello"));//true
console.log(str.endsWith(".vue"));//true
console.log(str.includes("e"));//true
console.log(str.includes("hello"));//true

字串模板

let ss = `<div>
                    <span>hello world<span>
                </div>`;
        console.log(ss);

字串插入變數和表示式

function fun() {
            return "這是一個函式"
        }

let info = `我是${abc},今年${age + 10}了, 我想說: ${fun()}`;
console.log(info);

函式最佳化

// 函式預設值
        function add2(a, b = 1) {
            return a + b;
        }
        console.log(add2(20));

// 不定引數
        function fun(...values) {
            console.log(values.length)
        }
        fun(1, 2)      //2
        fun(1, 2, 3, 4)  //4

// 箭頭函式,箭頭函式this不能使用,物件.屬性
// 例
let print = obj => console.log(obj);
        print("hello");

// 例
let sum2 = (a, b) => a + b;
        console.log(sum2(11, 12));

// 例
const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }
let hello2 = ({name}) => console.log("hello," +name);
        hello2(person);

物件最佳化

        const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }

        console.log(Object.keys(person));//["name", "age", "language"]
        console.log(Object.values(person));//["jack", 21, Array(3)]
        console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]

// 物件合併
        const target = { a: 1 };
        const source1 = { b: 2 };
        const source2 = { c: 3 };

        //{a:1,b:2,c:3}
        Object.assign(target, source1, source2);

// 物件的函式屬性簡寫
        let person3 = {
            name: "jack",
            // 以前:
            eat: function (food) {
                console.log(this.name + "在吃" + food);
            },
            //箭頭函式this不能使用,物件.屬性
            eat2: food => console.log(person3.name + "在吃" + food),
            eat3(food) {
                console.log(this.name + "在吃" + food);
            }
        }

// 物件深複製
        let p1 = { name: "Amy", age: 15 }
        let someone = { ...p1 }
        console.log(someone)  //{name: "Amy", age: 15}

// 合併物件
        let age1 = { age: 15 }
        let name1 = { name: "Amy" }
        let p2 = {name:"zhangsan"}
        p2 = { ...age1, ...name1 } 
        console.log(p2)

陣列新增 map, reduce

//陣列中新增了map和reduce方法。
        //map():接收一個函式,將原陣列中的所有元素用這個函式處理後放入新陣列返回。
         let arr = ['1', '20', '-5', '3'];
arr = arr.map(item=> item*2);


        //reduce() 為陣列中的每一個元素依次執行回撥函式,不包括陣列中被刪除或從未被賦值的元素,
        //[2, 40, -10, 6]
        //arr.reduce(callback,[initialValue])
        /**
        1,2,3,4 分別表示引數的位置
         1、previousValue (上一次呼叫回撥返回的值,或者是提供的初始值(initialValue))
    2、currentValue (陣列中當前被處理的元素)
    3、index (當前元素在陣列中的索引)
    4、array (呼叫 reduce 的陣列)*/
        let result = arr.reduce((a,b)=>{
            console.log("上一次處理後:"+a);
            console.log("當前正在處理:"+b);
            return a + b;
        },100);
        console.log(result)

promise 非同步操作

function get(url, data) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            data: data,
            success: function (data) {
                resolve(data);
            },
            error: function (err) {
                reject(err)
            }
        })
    });
}

get("mock/user.json")
    .then((data) => {
        console.log("使用者查詢成功~~~:", data)
        return get(`mock/user_corse_${data.id}.json`);
    })
    .then((data) => {
        console.log("課程查詢成功~~~:", data)
        return get(`mock/corse_score_${data.id}.json`);
    })
    .then((data)=>{
        console.log("課程成績查詢成功~~~:", data)
    })
    .catch((err)=>{
        console.log("出現異常",err)
    });

模組化

在 anyproxy 中,嘗試過濾請求資料,生成指定物件

const request = require('request');

const testRecordURL = 'https://testx.com';
const preRecordURL = 'https://prex.com';
const prdRecordURL = 'https://prodx.com';

module.exports = {

  *beforeDealHttpsRequest(requestDetail) {
    return true;
  },
  *beforeSendRequest(requestDetail) {
    if (requestDetail.requestOptions.method === 'GET') {
      if (requestDetail.url.indexOf(testRecordURL) === 0 ||
          requestDetail.url.indexOf(preRecordURL) === 0 ||
          requestDetail.url.indexOf(prdRecordURL) === 0) {
        const apiTestCase = {};
        apiTestCase.url = {};
        apiTestCase.caseInfo = {};
        apiTestCase.method = 'GET';
        apiTestCase.caseInfo.caseOwner = 'record';
        apiTestCase.caseInfo.caseComment = 'record by proxy tool';
        apiTestCase.contentType = {};
        apiTestCase.asserts = {};
        apiTestCase.asserts.responseCode = 200;
        apiTestCase.requestHeader = {};
        apiTestCase.requestParameter = {};

        if (requestDetail.url.indexOf(testRecordURL) === 0) {
          apiTestCase.url.baseUrl = testRecordURL;
          apiTestCase.caseInfo.caseName = 'test--';
        } else if (requestDetail.url.indexOf(preRecordURL) === 0) {
          apiTestCase.url.baseUrl = preRecordURL;
          apiTestCase.caseInfo.caseName = 'pre--';
        } else if (requestDetail.url.indexOf(prdRecordURL) === 0) {
          apiTestCase.url.baseUrl = prdRecordURL;
          apiTestCase.caseInfo.caseName = 'prd--';
        }

        if (requestDetail.requestOptions.path.indexOf('?') > 0) {
          const tempPath = requestDetail.requestOptions.path;
          apiTestCase.url.apiUrl = tempPath.substr(0, tempPath.indexOf('?'));
          apiTestCase.caseInfo.caseName += apiTestCase.url.apiUrl;

          const bodyArray = tempPath.substr(tempPath.indexOf('?') + 1).split('&');
          console.log('bodyArray', bodyArray);
          apiTestCase.requestParameter.reqBody = {};
          for (let i = 0; i < bodyArray.length; i++) {
            const attr = bodyArray[i].split('=');
            apiTestCase.requestParameter.reqBody[attr[0]] = attr[1];
          }
        } else {
          apiTestCase.caseInfo.caseName += requestDetail.requestOptions.path;
          apiTestCase.url.apiUrl = requestDetail.requestOptions.path;
          if (typeof (requestDetail.requestData) !== 'undefined') {
            if (Buffer.isBuffer(requestDetail.requestData)) {
              const tempReqBody = requestDetail.requestData.toString();
              if (tempReqBody === '') {
                apiTestCase.requestParameter.reqBody = {};
              } else {
                apiTestCase.requestParameter.reqBody = { buffer: 'error record' };
              }
            } else {
              apiTestCase.requestParameter.reqBody = requestDetail.requestData;
            }
          }
        }

    for (const key in requestDetail.requestOptions.headers) {
          if (key.toLocaleLowerCase() === 'accept-encoding') {
            delete (requestDetail.requestOptions.headers[key]);
          }
        }
        apiTestCase.requestHeader.headerMap = requestDetail.requestOptions.headers;

        if (typeof (requestDetail.requestOptions.headers['Content-Type']) !== 'undefined') {
          const jsonReg = new RegExp(/json/, 'i');
          const formReg = new RegExp(/form/, 'i');
          const multiFormReg = new RegExp(/multipart/, 'i');
          if (jsonReg.test(requestDetail.requestOptions.headers['Content-Type'])) {
            apiTestCase.contentType.request = 'json';
          } else if (multiFormReg.test(requestDetail.requestOptions.headers['Content-Type'])) {
            apiTestCase.contentType.request = 'multiForm';
          } else if (formReg.test(requestDetail.requestOptions.headers['Content-Type'])) {
            apiTestCase.contentType.request = 'form';
          }
        }

        console.log('apiTestCase', apiTestCase);

        request({
          url: 'http://qa.gegejia.com/apitest/autotestserver/saverecordrequest',
          method: 'POST',
          json: true,
          headers: {
            'content-type': 'application/json',
          },
          body: apiTestCase
        });

        return requestDetail;
      }
    }
  }
};

相關文章