ES6简记

作者: 公纸晓白 | 来源:发表于2019-04-03 11:21 被阅读0次

1.ES6箭头函数

//常规函数
function myname(a){
return a;
}
myname("a");// a
//等价于箭头函数
var myname=a=>a;
myname("a");// a
//其他复杂箭头函数
//无参数须加小括号,后面复杂运算加大括号,参数“,”隔开
var log = () => {
    alert('no param')
}
var add = (a, b) => a + b
add(3, 8) // 11
//返回对象时需要用小括号包起来,因为大括号被占用解释为代码块了
var getHash = arr => {
    // ...
    return ({
        name: 'Jack',
        age: 33
    })
}
//数组排序调用
var arr = [1, 9 , 2, 4, 3, 8].sort((a, b) => {
    if (a - b > 0 ) {
        return 1
    } else {
        return -1
    }
})
arr // [1, 2, 3, 4, 8, 9]

2.字符串

//常规用法
var a='hello ';
console.log(a+"world");//hello world
//es6用法
const a='hello ';
console.log(`${a}world`);//hello world
//使用${}界定字符串
//反引号(``)连接多行字符串
   const template = `<div>
        <span>hello world</span>
    </div>`

其他用法

// 1.includes:判断是否包含然后直接返回布尔值
    const  a = 'qwert'
    console.log(str.includes('w')) // true

    // 2.repeat: 获取字符串重复n次
    const str = 'he'
    console.log(str.repeat(3)) // 'hehehe'
    //如果你带入小数, Math.floor(num) 来处理,皆舍去
    // s.repeat(3.1) 或者 s.repeat(3.9) 都当做成 s.repeat(3) 来处理

    // 3. startsWith 和 endsWith 判断是否以 给定文本 开始或者结束
    const str =  'hello world!'
    console.log(str.startsWith('hello')) // true
    console.log(str.endsWith('!')) // true
    
    // 4. padStart 和 padEnd 填充字符串,应用场景:时分秒
    setInterval(() => {
        const now = new Date()
        const hours = now.getHours().toString()
        const minutes = now.getMinutes().toString()
        const seconds = now.getSeconds().toString()
        console.log(`${hours.padStart(2, 0)}:${minutes.padStart(2, 0)}:${seconds.padStart(2, 0)}`)
    }, 1000);

//模拟字符串实例

    let address = '北京海淀区'
    let name = 'lala'
    let str = '${name}在${address}上班...'
    // 模拟一个方法 myTemplate(str) 最终输出 'lala在北京海淀区上班...'
    function myTemplate(str) {

     var  str='return '+'`'+str+'`';
     let func = new Function('name','address', str);
     return func(name,address)

    }
    console.log(myTemplate(str))
//其他实例
//真实意义 tag(['Hello ', ' world ', ''], 15, 50)
let a = 5;
let b = 10;

function tag(s, v1, v2) {
  console.log(s[0]);
  console.log(s[1]);
  console.log(s[2]);
  console.log(v1);
  console.log(v2);
  return "OK";
}
tag`Hello ${ a + b } world ${ a * b}`;
// "Hello "
// " world "
// ""
// 15
// 50
// "OK"

相关文章

网友评论

      本文标题:ES6简记

      本文链接:https://www.haomeiwen.com/subject/qezrwftx.html