ES6常用API 及用法

* let { foo, bar } = { foo: "aaa", bar: "bbb" };

foo // "aaa"

bar // "bbb"

 

* function add(...values) {

  let sum = 0;

 

  for (var val of values) {

    sum += val;

  }

 

  return sum;

}

 

add(2, 5, 3) // 10

 

 

* var sum = (num1, num2) => { return num1 + num2; }

 

* 箭头函数有几个使用注意点。

1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。

3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。

4)不可以使用yield命令,因此箭头函数不能用作 Generator 函数。

*  foo::bar;

// 等同于

bar.bind(foo);

 

foo::bar(...arguments);

// 等同于

bar.apply(foo, arguments);

 

* var method = obj::obj.foo;

// 等同于

var method = ::obj.foo;

 

let log = ::console.log;

// 等同于

var log = console.log.bind(console);

 

*  function push(array, ...items) {

  array.push(...items);

}

 

function add(x, y) {

  return x + y;

}

 

const numbers = [4, 38];

add(...numbers) // 42

 

* // ES5 的写法

Math.max.apply(null, [14, 3, 77])

 

// ES6 的写法

Math.max(...[14, 3, 77])

 

// 等同于

Math.max(14, 3, 77);

 

* // ES5的 写法

var arr1 = [0, 1, 2];

var arr2 = [3, 4, 5];

Array.prototype.push.apply(arr1, arr2);

 

// ES6 的写法

let arr1 = [0, 1, 2];

let arr2 = [3, 4, 5];

arr1.push(...arr2);

 

 

*  const a1 = [1, 2];

// 写法一

const a2 = [...a1];

// 写法二

const [...a2] = a1;

 

 

* // ES5

[1, 2].concat(more)

// ES6

[1, 2, ...more]

 

var arr1 = ['a', 'b'];

var arr2 = ['c'];

var arr3 = ['d', 'e'];

 

// ES5的合并数组

arr1.concat(arr2, arr3);

// [ 'a', 'b', 'c', 'd', 'e' ]

 

// ES6的合并数组

[...arr1, ...arr2, ...arr3]

// [ 'a', 'b', 'c', 'd', 'e' ]

 

* [...'hello']

// [ "h", "e", "l", "l", "o" ]

 

 

* let map = new Map([

  [1, 'one'],

  [2, 'two'],

  [3, 'three'],

]);

 

let arr = [...map.keys()]; // [1, 2, 3]

 

* let arrayLike = {

    '0': 'a',

    '1': 'b',

    '2': 'c',

    length: 3

};

 

// ES5的写法

var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

 

// ES6的写法

let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

 

 

* // NodeList对象

let ps = document.querySelectorAll('p');

Array.from(ps).forEach(function (p) {

  console.log(p);

});

 

// arguments对象

function foo() {

  var args = Array.from(arguments);

  // ...

}

 

 

* Array.from('hello')

// ['h', 'e', 'l', 'l', 'o']

 

let namesSet = new Set(['a', 'b'])

Array.from(namesSet) // ['a', 'b']

 

 

 

* Array.of(3, 11, 8) // [3,11,8]

Array.of(3) // [3]

Array.of(3).length // 1

 

 

* Array(3, 11, 8) // [3, 11, 8]

// 3号位复制到0号位

[1, 2, 3, 4, 5].copyWithin(0, 3, 4)

// [4, 2, 3, 4, 5]

 

// -2相当于3号位,-1相当于4号位

[1, 2, 3, 4, 5].copyWithin(0, -2, -1)

// [4, 2, 3, 4, 5]

 

// 3号位复制到0号位

[].copyWithin.call({length: 5, 3: 1}, 0, 3)

// {0: 1, 3: 1, length: 5}

 

// 2号位到数组结束,复制到0号位

let i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);

// Int32Array [3, 4, 5, 4, 5]

 

// 对于没有部署 TypedArray copyWithin 方法的平台

// 需要采用下面的写法

[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);

// Int32Array [4, 2, 3, 4, 5]

 

*  [1, 4, -5, 10].find((n) => n < 0)

// -5

[1, 5, 10, 15].find(function(value, index, arr) {

  return value > 9;

}) // 10

 

 

*  [1, 5, 10, 15].findIndex(function(value, index, arr) {

  return value > 9;

}) // 2

 

 

*  ['a', 'b', 'c'].fill(7)

// [7, 7, 7]

 

new Array(3).fill(7)

// [7, 7, 7]

 

* ['a', 'b', 'c'].fill(7, 1, 2)

// ['a', 7, 'c']

 

* [1, 2, 3].includes(2)     // true

[1, 2, 3].includes(4)     // false

[1, 2, NaN].includes(NaN) // true

 

* [1, 2, 3].includes(3, 3);  // false

[1, 2, 3].includes(3, -1); // true

 

* const foo = 'bar';

const baz = {foo};

baz // {foo: "bar"}

 

// 等同于

const baz = {foo: foo};

 

 

* function f(x, y) {

  return {x, y};

}

 

// 等同于

 

function f(x, y) {

  return {x: x, y: y};

}

 

f(1, 2) // Object {x: 1, y: 2}

 

 

 

* Object.is('foo', 'foo')

// true

Object.is({}, {})

// false

 

 

* const target = { a: 1 };

 

const source1 = { b: 2 };

const source2 = { c: 3 };

 

Object.assign(target, source1, source2);

target // {a:1, b:2, c:3}

 

 

* const target = { a: 1, b: 1 };

 

const source1 = { b: 2, c: 2 };

const source2 = { c: 3 };

 

Object.assign(target, source1, source2);

target // {a:1, b:2, c:3}

 

 

* const obj = {a: 1};

Object.assign(obj) === obj // true

 

* typeof Object.assign(2) // "object"

 

* const v1 = 'abc';

const v2 = true;

const v3 = 10;

 

const obj = Object.assign({}, v1, v2, v3);

console.log(obj); // { "0": "a", "1": "b", "2": "c" }

 

* Object.assign({b: 'c'},

  Object.defineProperty({}, 'invisible', {

    enumerable: false,

    value: 'hello'

  })

)

// { b: 'c' }

 

 

 

* Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' })

// { a: 'b', Symbol(c): 'd' }

 

* const obj1 = {a: {b: 1}};

const obj2 = Object.assign({}, obj1);

 

obj1.a.b = 2;

obj2.a.b // 2

 

const target = { a: { b: 'c', d: 'e' } }

const source = { a: { b: 'hello' } }

Object.assign(target, source)

// { a: { b: 'hello' } }

 

 

* Object.assign([1, 2, 3], [4, 5])

// [4, 5, 3]

 

* const source = {

  get foo() { return 1 }

};

const target = {};

 

Object.assign(target, source)

// { foo: 1 }

 

class Point {

  constructor(x, y) {

    Object.assign(this, {x, y});

  }

}

 

 

Object.assign(SomeClass.prototype, {

  someMethod(arg1, arg2) {

    ···

  },

  anotherMethod() {

    ···

  }

});

 

// 等同于下面的写法

SomeClass.prototype.someMethod = function (arg1, arg2) {

  ···

};

SomeClass.prototype.anotherMethod = function () {

  ···

};

 

 

 

* function clone(origin) {

  return Object.assign({}, origin);

}

 

 

* function clone(origin) {

//继承

  let originProto = Object.getPrototypeOf(origin);

  return Object.assign(Object.create(originProto), origin);

}

 

* const merge =

  (target, ...sources) => Object.assign(target, ...sources);

 

 

* const merge =

  (...sources) => Object.assign({}, ...sources);

 

 

* const DEFAULTS = {

  logLevel: 0,

  outputFormat: 'html'

};

 

function processContent(options) {

  options = Object.assign({}, DEFAULTS, options);

  console.log(options);

  // ...

}

 

 

* const DEFAULTS = {

  url: {

    host: 'example.com',

    port: 7070

  },

};

 

processContent({ url: {port: 8000} })

// {

//   url: {port: 8000}

// }

 

 

* var obj = { foo: 'bar', baz: 42 };

Object.keys(obj)

// ["foo", "baz"]

 

 

* let {keys, values, entries} = Object;

let obj = { a: 1, b: 2, c: 3 };

 

for (let key of keys(obj)) {

  console.log(key); // 'a', 'b', 'c'

}

 

for (let value of values(obj)) {

  console.log(value); // 1, 2, 3

}

 

for (let [key, value] of entries(obj)) {

  console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]

}

 

 

* const obj = { foo: 'bar', baz: 42 };

Object.values(obj)

// ["bar", 42]

 

 

* const obj = { 100: 'a', 2: 'b', 7: 'c' };

Object.values(obj)

// ["b", "c", "a"]

 

 

* const obj = Object.create({}, {p: {value: 42}});

Object.values(obj) // []

 

 

* const obj = Object.create({}, {p:

  {

    value: 42,

    enumerable: true

  }

});

Object.values(obj) // [42]

 

 

* Object.values({ [Symbol()]: 123, foo: 'abc' });

// ['abc']

 

 

* Object.values('foo')

// ['f', 'o', 'o']

 

 

* Object.values(42) // []

Object.values(true) // []

 

 

* const firstName = message?.body?.user?.firstName || 'default';

 

 

* const obj = {};

let a = Symbol('a');

let b = Symbol('b');

 

obj[a] = 'Hello';

obj[b] = 'World';

 

const objectSymbols = Object.getOwnPropertySymbols(obj);

 

objectSymbols

// [Symbol(a), Symbol(b)]

 

 

 

* // 生成一个Promise对象的数组

const promises = [2, 3, 5, 7, 11, 13].map(function (id) {

  return getJSON('/post/' + id + ".json");

});

 

Promise.all(promises).then(function (posts) {

  // ...

}).catch(function(reason){

  // ...

});

 

 

 

*   var sum = (array, ...item) => {

        item.forEach(function(item) {

            array.push(item);

            console.log(item);

        });

         

        return array

    }

      const array1 = [

          ...['H'],

     'e'

      ];

sum(array1,'l','l','o')

 

 

 

* @testable

class MyTestableClass {

  // ...

}

 

function testable(target) {

  target.isTestable = true;

}

 

MyTestableClass.isTestable // true

 

 

 

* Ajax中使用promise

const getJSON = function(url) {

  const promise = new Promise(function(resolve, reject){

    const handler = function() {

      if (this.readyState !== 4) {

        return;

      }

      if (this.status === 200) {

        resolve(this.response);

      } else {

        reject(new Error(this.statusText));

      }

    };

    const client = new XMLHttpRequest();

    client.open("GET", url);

    client.onreadystatechange = handler;

    client.responseType = "json";

    client.setRequestHeader("Accept", "application/json");

    client.send();

 

  });

 

  return promise;

};

 

getJSON("/posts.json").then(function(json) {

  console.log('Contents: ' + json);

}, function(error) {

  console.error('出错了', error);

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值