概念: 先解構再賦值,先從一堆數據中找出本身須要的數據,而後將找到的數據賦值給事先定義好的變量css
// 對象的解構賦值 // 使用場景 // 1,等號右邊是大json,等號左邊是變量,這樣可快速獲取大json中數據,後續可進行push到數組等一系列操做 // 2,react在render中,直接對組件props或state進行解構賦值以後,在渲染頁面直接使用該數據 const response = { foo: 'aaa', bar: 'bbb', result: 'hello world'} // 這個數據通常是ajax請求獲得 let { foo, bar } = response // 拿請求數據中對本業務有用的數據 let result = [] result.push({ foo, bar }) console.log(foo) // aaa console.log(bar) // bbb console.log(result) // [ { foo: 'aaa', bar: 'bbb' } ] // 對象接口中key的命名是下劃線方式,而前端使用駱駝方式,能夠在解構的時候,直接賦予它別名,demo以下 const { cc_dd: ccDd } = response console.log('cc_dd解構賦值別名使用: ', ccDd) // 數組的解構賦值 /*解構: 從數組和對象中提取值,對變量進行賦值,若是解構不成功,直接undefined*/ let [a, b, c] = [1, 11, 12] console.log(a) // 1 console.log(b) // 11 console.log(c) // 12 let [d, e] = [1] console.log(e) // undefined let [head, ...tail] = [1, 2, 3, 4] console.log(head) // 1 console.log(tail) // [2, 3, 4] // 如下這種是不徹底解構 let [f, g] = [1, 2, 3] console.log(f) // 1 console.log(g) // 2 // 解構的時候,能夠設置默認值,這樣就不會undefined let [h, i = 1212] = [1] console.log(h) console.log(i)
{ /* * 擴展運算符: 數組前面加..., 可直接把數組中內容提取出來 * */ console.log('-------------擴展運算符-------------') const array1 = [1, 2, 3] const array2 = [4, 5, 6] console.log(...array1) console.log(1, ...[2,3,4], 5) function add(a, b) { return a + b } console.log(add(...array1)) console.log('返回值是數組的長度: ' + array1.push(...array2)) console.log(array1) console.log('ES6寫法,求數據中最大值: ' + Math.max(...[1,2,3])) // 3 const copyArray = [...array2] console.log(copyArray instanceof Array) console.log(copyArray) console.log([...'hello world']) // 將字符串轉換成數組 } { /* * Array.from(): 將相似數組對象轉換成數組,好比 document.querySelectorAll('p')獲取到全部p標籤集合就是相似數組對象 * * */ console.log('------------Array.from()-------------') const likeArray = { '0': 'a', '1': 'b', '2': 'c', 'length': 3, 'name': 'wujiedong' } const array = Array.from(likeArray) console.log(array) /*const p = document.querySelectorAll('p') Array.from(p).filter(item => { return item.textContent.length > 100 })*/ } { /* * Array.of(): 將一組值轉換成數組,它直接替代了 new Array()和Array() * */ console.log('------------Array.of()-------------') console.log(Array.of('北京', '上海', '廣州')) } { /* * find():參數傳遞一個function,查找第一個符合條件的數組元素,返回該元素的值 * findIndex():參數傳遞一個function,查找第一個符合條件的數組元素,返回該元素在數組中位置 * */ console.log('------------find()和findIndex()------------') const array = [1, 22, 33, 44, 55, 56] const result = array.find((item, index, array) => { /*(當前值,當前位置,原數組)*/ return item > 23 }) console.log(result) const index = array.findIndex((item, index) => { if (item > 23) { return index } }) console.log(index) } { /* * 數組中是否包含某個元素 * Array.includes(參數1, 參數2) 參數1: 查詢的參數 參數2: 查詢位置,若是是負數,表示倒數的位置 * */ console.log('------------includes()------------') const array = [1, 22, 33, 44, 55, 56] console.log(array.includes(1)) console.log(array.includes(1, 0)) console.log(array.includes(1, 2)) } { /* * 數組實例的 entries(),keys() 和 values() * entries: key-value的遍歷 * keys: key的遍歷 * values: value的遍歷 * */ console.log('------------entries(),keys() 和 values()------------') for (let [index, elem] of ['a', 'b'].entries()) { console.log(index, elem); } }
/* 寫法1: 先單獨定義,而後一次性export,導出須要加上{} let name = 'wujiedong' const getName = function () { console.log('getName') } export { name, getName }*/ /* * 寫法2: 每寫一個變量就進行一次導出 * */ export const name = 'wujiedong' export const getName = () => { console.log('getName') } /* * 上述2種方式的導出,在import導入的時候,若是要使用,須要指定導入名字,好比 export中name,那在import的時候需指定name一致,並且必須加上{} * */ /*export default * 導出的時候不指定名字,這樣若是import須要使用了,直接 import xxx from 'js路徑' , xxx可隨意定義名字,不須要加{} * */ export default function foo() { console.log('foo'); } export default { name: '中國', setName: function (name) { this.name = name }, getName: function () { return this.name }, doubleName: function () { console.log(this) const result = () => this.name + '====' + this.name return result() // 這裏能夠正常輸出 } /*sayHello: () => { console.log(this) undefined }*/ } /* 這種方式的導出是錯誤,它導出的不是接口,是一個數值 var i = 1 export i // 報錯 function f() {} export f; // 正確 export function f() {}; // 正確 function f() {} export {f}; */
最佳實踐,對整個項目接口地址進行單獨js文件管理html
// config.js單獨文件維護 // import { constants } from 'config.js路徑'便可使用接口地址 // 單獨將serverAddress服務器地址抽取出來,生產和開發通常都是2個不一樣服務器 const serverAddress = 'http://10.12.3.80:8080' // jinfeng // const serverAddress = 'http://20.78.14.88:8888' // qinghai export const constants = { searchTimeDateApi: serverAddress + '/qh_plat/met_plot/wea_fore/timebar', picdzApi: serverAddress + '/qh_plat/met_plot/wea_fore/jsondata', searchSelectCjApi: serverAddress + '/qh_plat/met_plot/wea_fore/config?source=qh', weatherApi: serverAddress + '/qh_plat/met_stations/wea_std/stations', weatherDetailApi: serverAddress + '/qh_plat/met_stations/wea_std/forecast', }
{ console.log('-----------------------------Object.is()-----------------------------') /*Object.is() 同值相等,若是比較的是對象,那就是false*/ const a1 = { name: 'zhangsan', hobbies: ['看書', '學習'] } const a2 = { name: 'zhangsan', hobbies: ['看書', '學習'] } console.log(Object.is(a1, a2)) // false const a3 = 'hello world' const a4 = 'hello world' console.log(Object.is(a3, a4)) // true const a5 = { name: 'zhangsan' } const a6 = { name: 'zhangsan' } console.log(Object.is(a5, a6)) // false } { console.log('-----------------------------Object.assign()-------------------------------') /*Object.assign() 對象複製,將源對象可枚舉的所有複製到目標對象,不會改變源對象的值 * 參數1: 目標對象, 參數2到N,源對象, 把從參數2到N -> 參數1目標對象 * 目標對象和源對象有相同的key,後面key中value會覆蓋前面key中value * 是淺拷貝,若是value是對象,那拷貝的是引用,不是值 * */ const a1 = { name: 'zhangsan', } const a2 = { hobbies: ['看書', '學習'], json: { age: 12 } } const a3 = { birthday: '2019-11-11' } const target = {} Object.assign(target, a1, a2, a3) console.log('target: ', target) console.log('a1: ', a1) console.log('a2: ', a2) a2.hobbies.push('睡覺') a2.json.age = 22 console.log('target中hobbies的值: ', target.hobbies) console.log('a2中hobbies的值: ', a2.hobbies) console.log('target中hobbies數據類型: ', typeof target.hobbies) console.log('a2中hobbies數據類型: ', typeof a2.hobbies) console.log('target中json: ', target.json) console.log('a2中json: ', a2.json) a1.name = 'lisi' console.log('a1中name的類型: ',typeof a1.name) console.log('target中name的類型: ',typeof target.name) console.log('a1中name的值: ', a1.name) // lisi console.log('target中name的值: ', target.name) // zhangsan // 最佳實踐 /* * 需求: 將數組[{id: 0, date: '2012-12-12'}, {id: 1, date: '2012-12-13'}, {id: 2, date: '2012-12-14'}] * 轉成對象 {1: '2012-12-12', 2: '2012-12-13', 3: '2012-12-14'} * 在ant的Slider組件中,作一個關於日期數據的組件,就可使用該最佳實踐 * */ const dates = [ {id: 0, date: '2012-12-12'}, {id: 1, date: '2012-12-13'}, {id: 2, date: '2012-12-14'} ] let dateObj = {} for (let item of dates) { const { id, date } = item const temp = {[id]: date} // id是變量,在json中key若是是變量,必須加上[] Object.assign(dateObj, temp) } console.log('dateObj', dateObj) //{ '0': '2012-12-12', '1': '2012-12-13', '2': '2012-12-14' } } { let a = { name: 'wujiedon' } const b = a a.name = 'zhangsan' console.log(b.name) let c = ['zhangsan', 'lisi'] const d = c c.push('wangwu') console.log(d) } { console.log('---Object.entries()---') /*Object.entries(): 將一個對象變成數組 * 需求: 將 {a: 1, b: 2, c: 3} => {[{name: 'a', value: 1}, {name: 'b', value: 2}, {name: 'c', value: 3}]} * 服務器接口中若是返回的json,其中key是一個變量,就能夠經過該需求,轉換成正常的json數據 * */ const obj = {a: 1, b: 2, c: 3} console.log(Object.entries(obj)) // [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ] const result = Object.entries(obj).map(item => { return {name: item[0], value: item[1]} }) /* 輸出: * [ { name: 'a', value: 1 }, { name: 'b', value: 2 }, { name: 'c', value: 3 } ] * */ console.log(result) }
/*概念: 使用 ... 取出參數對象中全部可遍歷的屬性,拷貝到當前對象中 * 在React框架的開發中,在處理state數據的時候,會常常使用該技巧 * */ { const state = { name: 'zhangsan', age: 30, city: 'wuxi' } // 使用擴展運算符完成對象屬性拷貝,在react中,子組件接收父組件state,可直接拷貝,而後再接着寫本身的屬性 const copyState = { ...state, // 從父組件拷貝過來的組件 bithday: '2011-11-11', // 本身的屬性 country: 'china' } console.log(state) console.log(copyState) // 擴展運算符後面可跟表達式,表達式以後,還能再寫屬性 const a = 1 const info = { ...(a > 1 ? {b: 111} : {b: 222}), c: 333 } console.log(info) } { /*擴展運算符,實現舊json對新json的複製*/ const food = { id: 1, name: '雪花啤酒', amount: 12, price: 3.2, type: '飲料' } const newFood = { ...food, amount: 0 } console.log(newFood) }
{ /*屬性和function的簡潔寫法*/ let birthday = '2012-11-11' /*ES6寫法*/ const person = { name: 'zhangsan', birthday, sayInfo() { console.log('person info:' , this.name, this.birthday) } } /*等價*/ const oldPerson = { name: 'zhangsan', birthday: birthday, sayInfo: function () { console.log('person info:' , this.name, this.birthday) } } person.sayInfo() oldPerson.sayInfo() console.log(oldPerson.sayInfo.name) // 返回函數名字 for (let key in oldPerson) { console.log(key) } } { /*看成函數返回值*/ function getPoint(x, y) { return {x, y} } console.log(getPoint(1, 2)) /*{ x: 1, y: 2 }*/ }
// js /*let name = 'wujiedong' let age = 29 let html = '<div>' html += ' <p>' + name + '</p>' html += ' <p>' + age + '</p>' html += ' </div>' console.log(html)*/ // ES6 const name = 'wujiedong' const age = 29 const html = `<div> <p>${name}</p> <p>${age}</p> </div>` console.log(html) /*最佳實踐1: 根據傳入參數組裝url接口地址,這樣能夠少寫不少+號*/ function getApi(name, age) { return `http://127.0.0.1:8888?name=${name}&age=${age}` } const api = getApi('wujiedong', 29) console.log('api:', api) /*最佳實踐2: 在React開發中,不免會在js文件中寫一些css代碼,這種情景,就可使用多行字符串 * 如下是一段僞代碼 * */ const myCustomColour = 'red' // 抽取頁面常常需求變更的數據變量 const markStyle = ` background-color:${myCustomColour}; display:block; border-radius:5px; width:6px; height:6px;`; console.log('markStyle', markStyle)
{ const city = 'wuxi' console.log(city.indexOf('w')) // 0 ES5, 字符串存在,返回0 console.log(city.indexOf('wx')) // -1 字符串不存在,返回 -1 console.log(city.includes('wux')) // true ES6, 返回boolean值 表示是否找到了參數字符串。 console.log(city.startsWith('w')) // true ES6, 返回boolean值 表示參數字符串是否在原字符串的頭部。 console.log(city.endsWith('xi')) // true ES6, 返回boolean值 表示參數字符串是否在原字符串的尾部。 console.log(city.repeat(2)) // wuxiwuxi 返回一個新字符串,表示將原字符串重複n次。 }