JavaScript之字符的使用

字符

连接/变量输出

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)
    
  • 文献

    解构赋值

    Destructuring assignment

    [ES6 JavaScript Destructuring in Depth](

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值