【ES2017】ES8新增特性- 字符串补全、对象方法

1. 字符串实例新增方法

新增了补全长度方法 padStart()padEnd(),该方法可以使得字符串达到固定长度。它有两个参数,字符串目标长度和填充内容。。

'x'.padStart(7, 'abc') // 'abcabcx'
'x'.padStart(5, 'abc') // 'abcax'

'x'.padEnd(7, 'abc') // 'xabcabc'
'x'.padEnd(5, 'abc') // 'xabca'

2. 函数新增特性

ES2017 允许函数的最后一个参数有尾逗号(trailing comma)。此前,函数定义和调用时,都不允许最后一个参数后面出现逗号。

function clownsEverywhere(param1,param2,) {
    
     
  /* ... */ 
}
clownsEverywhere('foo','bar',);

3. Object 构造函数本身新增方法

3.1 Object.entires()Object.values()

ES2017引入,Object.entries()方法返回一个数组,将对象自身的(不含继承的)所有可遍历(enumerable)属性与键值 以按照二维数组的方式返回。(如果目标对象是数组,则会将数组的下标作为键值返回)

Object.entries({
    
     one: 1, two: 2 })    //[['one', 1], ['two', 2]]
Object.extries([1, 3])    //[['0', 1], ['1', 3]]
ES2017引入,`Object.values()`方法返回一个数组,将对象自身的(不含继承的)所有可遍历(`enumerable`)属性的键值 以数组形式返回。其工作原理和`Object.entries()`方法很像,但是它只返回键值对中的值,结果是一维数组
Object.values({
    
    one: 1, two: 2})    // [1, 2]
Object.values({
    
    3: 'a', 1: 'b', 2: 'c'}) // ['b', 'c', 'a'] 
Object.extries([1, 3])     //[1, 3]
3.2 Object.fromEntries()方法

Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。

Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }
3.3 Object.getOwnPropertyDescriptors()方法

ES5中Object.getOwnPropertyDescriptor()方法会返回某个对象属性的描述对象(descriptor)。ES2017引入了Object.getOwnPropertyDescriptors()方法,返回指定对象所有自身属性(非继承属性)的描述对象。

const obj = {
    
    
  foo: 123,
  get bar() {
    
     return 'abc' }
};
Object.getOwnPropertyDescriptors(obj)
// { foo:
//    { value: 123,
//      writable: true,
//      enumerable: true,
//      configurable: true },
//   bar:
//    { get: [Function: get bar],
//      set: undefined,
//      enumerable: true,
//      configurable: true } 
//}

猜你喜欢

转载自blog.csdn.net/qq_38987146/article/details/121378231