本文主要讲解 ES8 ( ES2017 ) 新增的几个常用功能、特性
字符串填充,两个新函数:padStart 和 padEnd
padStart 和 padEnd 一共接受两个参数
第一个参数用来指定结果字符串的最小长度,第二个参数是指用来补全的字符串。
注意:如果第一个参数的值小于或等于原字符串的长度,则返回原字符串。如果省略第二个参数,默认使用空格补全长度。
几个栗子:
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
一种用法:
提示字符串格式。
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
values和entries函数
这两个函数都是 Object 的方法,调用方法为:
Object.values(obj)
Object.entries(obj)
Object.values 函数返回一个数组,该数组的内容是函数参数的可遍历属性的属性值。
Object.entries 函数也是返回一个数组,只不过这个数组是一个以参数的可枚举属性的键值对为数组 [key, value] 的 n 行 2 列的数组。
看几个栗子就很明白了:
const obj = { x: 'xxx', y: 1 };
Object.values(obj); // ['xxx', 1]
Object.entries(obj); // [['x', 'xxx'], ['y', 1]]
const obj = ['e', 's', '8']; // same as { 0: 'e', 1: 's', 2: '8' };
Object.values(obj); // ['e', 's', '8']
Object.entries(obj); // [['0', 'e'], ['1', 's'], ['2', '8']]
getOwnPropertyDescriptors函数
依旧是 Object 的成员函数。该函数返回指定对象(参数)的所有自身属性描述符。
自身属性描述符:指的是在对象自身内定义,不是通过原型链继承来的属性。
const obj = {
get es7() { return 777; },
get es8() { return 888; }
};
Object.getOwnPropertyDescriptor(obj);
// {
// es7: {
// configurable: true,
// enumerable: true,
// get: function es7(){}, //the getter function
// set: undefined
// },
// es8: {
// configurable: true,
// enumerable: true,
// get: function es8(){}, //the getter function
// set: undefined
// }
// }
async 函数
看一个栗子:
const fs = require('fs');
const readFile = function (fileName) {
return new Promise(function (resolve, reject) {
fs.readFile(fileName, function(error, data) {
if (error) return reject(error);
resolve(data);
});
});
};
const asyncReadFile = async function () {
const f1 = await readFile('/etc/fstab');
const f2 = await readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
return f2.toString()
};
这里,函数 readFile 明显是一个异步函数,它返回了一个 Promise。
而函数 asyncReadFile 会自动执行,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句,最后得到结果。而调用 async 函数的时候,会立即返回一个Promise对象。因此可以这样写:
asyncReadFile('goog').then(function (result) {
console.log(result); // f2.toString() 的结果
});