let和const
- webpack构建的项目,直接废弃var,直接使用let代替var
- for循环中使用let而不是var
- 变量声明之后就不会改变,请使用const
解构赋值
概念: 先解构再赋值,先从一堆数据中找出自己需要的数据,然后将找到的数据赋值给事先定义好的变量
// 对象的解构赋值
// 使用场景
// 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);
}
}
Module语法
- export: 导出接口,使用{}将变量包裹起来,对外可以让其他js使用,import { 名字一致 } from 'js路径'
- export default: 导出接口,对外可以让其他js使用,import 名字随意起 from 'js路径'
- import: 导入,需要使用到其他js文件
/*
写法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文件管理
// 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)
ES6新增方法
{
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次。
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。