字符
连接/变量输出
const a = 20
const b = 10
const c = 'javascript'
// const str = 'my age is ' + (a + b) + ' i love ' + c
const str = `my age is ${a + b} i love ${c}`
console.log(str)
换行
let g = `我是第一行
换行了`
console.log(g)
/*
我是第一行
换行了
*/
字符串-函数
function Price (strings, type) {
let s1 = strings[0]
const retailPrice = 20
const wholeSalePrice = 16
let showTxt
if (type === 'retail') {
showTxt = '购买单价是:' + retailPrice
} else {
showTxt = '购买的批发价是:' + wholeSalePrice
}
// console.log(s1) // 您此次的
return `${s1}${showTxt}`
}
let showTxt = Price`您此次的${'retail'}`
console.log(showTxt)
解构赋值
let arr = ['hello', 'world']
let [firstName,surName] = arr // 解构赋值
console.log(firstName,surName) // hello world
-
选择
let arr = 'abcd' let [firstName, , thridName] = arr console.log(firstName, ,thridName) //a c
-
对象
let user = { name: 's', surname: 't' };// 对象要加分号 [user.name, user.surname] = [1, 2] console.log(user) // 1 2
-
显示
let arr = [1, 2, 3, 4, 5, 6, 7, 8] let [firstName, curName, ...last] = arr console.log(firstName, curName, last)
-
在解构赋值时若没有参数则显示
undefnd
-
若不想显示
undefind
则写成let [firstName=‘hello’, curName, ...last] = arr
-
对象取值
let options = { title: 'menu', // width: 100, height: 200 } let { title: title2, width = 130, height } = options console.log(title2, width, height)
只想关注某些变量
let options = { title: 'menu', width: 100, height: 200 } let { title, ...last } = options // menu {width: 100, height: 200}
复杂点的
let options = { size: { width: 100, height: 200 }, items: ['Cake', 'Donut'] } let { size: { width: width2, height }, items: [item1] } = options console.log(width2, height, item1)
-
文献
[ES6 JavaScript Destructuring in Depth](