js小技巧

69 阅读2分钟

转载请注明出处,谢谢

async/await

作用: async/await 是ES7提出的基于Promise的解决异步的最终方案
案例:

var sleep = function (time) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            // 返回 ‘ok’
            resolve('ok');
        }, time);
    })
};

var start = async function () {
    console.log(123);
    let result = await sleep(3000);
    console.log(result); 
    console.log(465);
}
start()
//结果
//1. 123
//2. ok
//3. 456

/** */ (注解)

作用: 其他地方使用该函数,鼠标悬停在上方,编辑器给出提示
案例:

/**
 * 滚动页面, 将最后一行移动至视区
 * @param {boolean} highlight 是否需要高亮指定行.
 */
function scrollToBottom (highlight = true) {
  scrollToRow(-1, highlight)
}

??(空值合并操作符)

作用:当??左侧值为 null 或 undefined 时,返回 ?? 符号右边的值
背景:??运算符是 es11(ES2020) 引入,也被称为null判断运算符( Nullish coalescing operator)
案例:

console.log('hello' ?? 'hi');      // 'hello'
console.log('hello' ?? 'hi');      // 'hello'
console.log('' ?? 'hi' );          // ''
console.log(false ?? 'hi' );       // false
console.log(null ?? 'hi'  );       // 'hi'
console.log(undefined ?? 'hi');    // 'hi'

?.(链判断运算符)

作用:?. 直接在链式调用的时候判断,判断左侧的对象是否为 null 或 undefined ,如果是的,就不再往下运算,返回 undefined,如果不是,则返回右侧的值。
背景:?.es11(ES2020) 引入,有人称为链判断运算符(optional chaining operator)
案例:

let obg = {
    age: 18,
    name: 'zhangsan'
}
console.log(obg?.name);     // 返回 zhangsan
console.log(obg?.sex);      // 返回 undefined

arr.at()

作用: 参数正数就表示顺数第几个,负数表示倒数第几个,这可以很方便的某个数组末尾的元素 案例:

var arr = [1, 2, 3, 4, 5]

console.log(arr.at(0))   // 1
console.log(arr.at(1))   // 2
console.log(arr.at(-1))  // 5
console.log(arr.at(-2))  // 4

Set()

作用: 过滤原数组重复值
背景: es6新特性
案例:

const arr = [1, 2, 3, 3, 5, 5, 1];
const newArr = new Set(arr);
console.log(newArr); // [1, 2, 3, 5]

三元运算符

作用: 很方便快捷的书写一些简单的逻辑语句的方式
案例:

var age = prompt('请输入你的年龄');
var str = age > 17 ? '成年了' : '没有成年';
console.log(str);

数据类型隐式转化

案例:

// 转换String型
const val = 1 + "";
console.log(val, typeof val);     // "1","string"

// 转换Number类型
let int1 = "15";
int1 = +int1;
console.log(int1, typeof int1);   // 15,"number"

let int2 = "15";
int2 = ~~int2;
console.log(int2, typeof int2);   // 15,"number"

// 转换Boolean型
const isTrue = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue, typeof isTrue);         // true,"boolean"
console.log(isFalse, typeof isFalse);       // false,"boolean"
console.log(alsoFalse, typeof alsoFalse);   // false,"boolean"