ES6之常用开发知识点:入门(一)

前端开发 作者: 2024-08-20 16:20:01
ES6介绍 ES6, 全称 ECMAScript 6.0 ,2015.06 发版。 let 和 const命令 let命令 let 命令,用来声明变量。它的用法类似于var,区别在于var声明的变量全

let命令

var a = [];
for (var i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 10
) {
    ((i){
        a[i] =  () {
          console.log(i);
        };
    })(i); 
}
a[6]();  6
for (let i = 0; i < 10; i++ 6
  • let 不存在变量提升,必须先声明后使用,否则报错;var存在变量提升,未声明前使用输出 undefined。
  • let 存在暂时性死区,在代码块内,使用let命令声明变量之前,该变量都是不可用的。
  • let 不允许重复声明。

const 命令

const a = 10;
a = 20;  报错

const b;  报错
if(true) {
  const num = 5;
}
console.log(num);  报错
const obj = {};
obj.a = 'a';

obj = {};  报错

块级作用域和函数作用域

var tmp = new Date();

 f() {
  console.log(tmp);
  if (false) {
    var tmp = 'hello world';
  }
}

f();  undefined
var s = 'hello';

var i = 0; i < s.length; i++) {
  console.log(s[i]);
}

console.log(i);  5
 f1() {
  let n = 5;
  ) {
    let n = 10;
  }
  console.log(n);  5
}
 IIFE 写法
( () {
  var tmp = ...;
  ...
}());

 块级作用域写法
{
  let tmp = ...;
  ...
}
 情况一
) {
   f() {}
}

 情况二
try {
   f() {}
} catch(e) {
   ...
}
function f() { console.log('I am outside!'); }

( 重复声明一次函数f
    function f() { console.log('I am inside!'); }
  }

  f();
}());
 ES5 环境
); }
  ) {
  }
  f();
}());
 浏览器的 ES6 环境
); }
  }

  f();
}());
 Uncaught TypeError: f is not a function
  • 允许在块级作用域内声明函数。
  • 函数声明类似于var,即会提升到全局作用域或函数作用域的头部。
  • 同时,函数声明还会提升到所在的块级作用域的头部。
); }
(var f = undefined;
   Uncaught TypeError: f is not a function
 第一种写法,报错
true) let x = 1 第二种写法,不报错
) {
  let x = 1;
}
 不报错
 报错
'use strict';
)
  function f() {}

数组的解构赋值

let [a,[[b],c]] = [1,[[2],3]];
console.log(a,b,c);  1,2,3

let [x,y,z] = [1,1)">];
console.log(x);  1
console.log(y);  3
console.log(z);  undefined
let [x,[y],z] = [1,[2,3],4 2
console.log(z);  4
let [a] = {};  报错
let [a = 1,b = 2] = [,1)">];
console.log(a);  1
console.log(b);  3

let [x = 1,y = x] = [];   x = 1; y = 1
let [x = 1,y = x] = [2];  x = 2; y = 2
let [a,b] = [1,2];
console.log(a,b);  [a,b];
console.log(a,1)"> 2,1

对象的解构赋值

let { a,c } = { a: 'aaa',b: 'bbb' };
console.log(a);  'aaa'
console.log(b);  'bbb'
console.log(c);  undefined
let { a: x,b: y } = { a: 'aaa',1)"> };
console.log(x);  'aaa'
console.log(y);  'bbb'
let { a,a: {x},b: y } = { a: {x: 'xxx',y: 'yyy'},b: "bbb" { x: 'xxx',y: 'yyy' }
console.log(x);  'xxx'

let {c: {d: {e}}} = {c: 'ccc'};  报错
console.log(e)

字符串解构赋值

const [a,c] = '123456789';
const {length} = '123456789';
console.log(a,c,length); 
let {length : len} = 'hello';
len  5

函数参数解构赋值

 add([x,y]){
  return x + y;
}

add([1,2]);  3
const arr = [[1,2],[3,4]].map(([a,b]) => a + b);
console.log(arr);  [ 3,7 ]
function move({x = 0,y = 0} = {}) {
  return [x,y];
}

move({x: 3,y: 8});  [3,8]
move({x: 3});  [0,0]
move(); 上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值。

function move({x,y} = { x: 0,y: 0 }) {
   [undefined,undefined]
move(); 字符串扩展

for...of 遍历字符串

for(let codePoint of 'string'){
  console.log(codePoint)
}
 's'
// 't' 'r' 'i' 'n' 'g'

includes(),startsWith(),endsWith()

let s = 'Hello world!';

const [a,c] = [
    s.startsWith('Hello',1)">),s.endsWith('!')
];

console.log(a,1)"> false true true

repeat()

  • 参数为[-Infinity,-1]或者 Infinity,会报错;
  • 参数为(-1,1)时,相当于参数为 0;
  • 参数为小数时向下取整;
  • 参数 NaN 等同于 0;
  • 参数是字符串,则会先转换成数字。
'str'.repeat('3')  'strstrstr'

padStart(),padEnd()

'123456'.padStart(10,'0')  "0000123456"
'09-12'.padStart(10,'YYYY-MM-DD')  "YYYY-09-12"

模版字符串(``)

const str = 'world';
const template = `Hello ${str}`;
console.log(template);  Hello world

二进制、八进制表示法

0b1100100 === 100;  true
0o144 === 100;  true

(0b1100100).toString(8);  144
(0b1100100).toString(10);  100
Number('0b1100100');  100

Number.isFinite(),Number.isNaN()

Number.isFinite(15);  true
Number.isFinite(-Infinity);  false

Number.isNaN(15)  false
Number.isNaN(9/0) // true

Number.parseInt(),Number.parseFloat()

Number.isInteger()

Number.isInteger(25)  true
Number.isInteger(25.0)  true
Number.isInteger(25.1)  false
  • Number.EPSILON 极小常量,浮点数误差小于这个值可以认为不存在误差;
  • Number.MAX_SAFE_INTEGER 安全整数的最大范围;
  • Number.MIN_SAFE_INTEGER 安全整数的最小范围;
  • Number.isSafeInteger() 用来判断一个整数是否落在安全整数范围之内。
Number.isSafeInteger(9007199254740993)  false
Number.isSafeInteger(990)  true
Number.isSafeInteger(9007199254740993 - 990)  true

Math 对象的扩展

Math.trunc(5.9)  5
Math.trunc(-4.9)  -4
Math.trunc(null)  0
Math.trunc('foo');  NaN
Math.sign(-5)  -1 负数
Math.sign(5)  +1 正数
Math.sign(0)  +0 零
Math.sign(-0)  -0 零
Math.sign(NaN)  NaN
Math.cbrt(2)   1.2599210498948734

 Math.sqrt(x) 计算平方根
Math.sqrt(2)  1.4142135623730951

 幂运算 Math.pow(x,y)
Math.pow(2,3)
Math.hypot(3,4);         5
Math.hypot(3,4,5);      7.0710678118654755

rest 参数

 sum1(x,...args) {
    let sum = 0;

    for (let arg of args) {
        sum += arg;
    }

     sum;
}

console.log(sum1(1,4))  7

 sum2(...args) {
    return args.reduce((prev,curr) => {
        return prev + curr
    },0)
}

console.log(sum2(1,3));  6

name 属性

 fn() {}
fn.name  'fn'

 foo() {};
foo.bind({}).name  'bound foo'

(new Function).name  "anonymous"
function(){}).bind({}).name  'bound '

箭头函数

const fn = v => v;

 等同于
const fn =  (v) {
   v;
};
  • 函数体内的 this 对象,就是定义时所在的对象,而不是使用时所在的对象;
  • 不可以当作构造函数,即不可以使用 new 命令,否则会抛出一个错误;
  • 不可以使用 arguments 对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替;
  • 不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数。

扩展运算符

const arr = [1,1)">];
arr.push(...[4,5,6]);
  • 数组展开
const arr = [1,1)">];
...arr 
  • 复制数组
  • const a1 = [1,1)">];
     写法一
    const a2 = [...a1];
     写法二
    const [...a2] = a1;
    
     相当于
    const a1 = [1,1)">];
    const a2 = a1.concat();
    • 解构赋值,字符串转数组
    const list = [1,1)">];
    [a,...b] = list;
    console.log(a)  1
    console.log(b)  [2,3]
    
    [...'hello']  ['h','e','l','o']

    Array.from()

    let arrayLike = {
        '0': 'a','1': 'b'3
    };
    
     ES5的写法
    var arr1 = [].slice.call(arrayLike);  ['a','b','c']
    
     ES6的写法
    let arr2 = Array.from(arrayLike); 
    Array.from('hello');
    
    let namesSet = new Set(['a','b']);
    Array.from(namesSet); 
    
    let arrayLike = {
        '0': 1'2': 3
    };
    Array.from(arrayLike,x => x * x);  [ 1,9 ]

    Array.of()

    Array.of()  []
    Array.of(undefined)  [undefined]
    Array.of(1)  [1]
    Array.of(1,2)  [1,2]

    copyWithin()

    • target(必需):必需。复制到指定目标索引位置。
    • start(可选):可选。元素复制的起始位置。
    • end(可选):可选。停止复制的索引位置(默认为array.length)。如果为负值,表示倒数。
    var result = [1,5].copyWithin(0,1)">) 
    console.log(result)[4,5]

    find() 和 findIndex()

    [1,-5,10].find(n => n < 0);  -5
    [1,10].findIndex(n => n < 0);  2
     f(v){
      return v > this.age;
    }
    let person = {name: 'John',age: 20};
    [10,12,26,15].find(f,person);   26

    fill() 填充数组

    let arr = Array.of(1,1)">).fill({
        num: 20
    });
    
    console.log(arr);  [ { num: 20 },{ num: 20 },{ num: 20 } ]
    
    arr[0].num = 10;
    console.log(arr);  [ { num: 10 },{ num: 10 },{ num: 10 } ]

    entries(),keys() 和 values() 遍历数组

    for (let index of ['a',1)">].keys()) {
      console.log(index);
    }
     0 1
    
    for (let elem of ['a',1)">].values()) {
      console.log(elem);
    }
     'a' 'b'
    
    for (let [index,elem] of ['a',1)">].entries()) {
      console.log(index,elem);
    }
     0 "a" 1 "b"

    includes()

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

    flat(),flatMap()

    [1,[3]]].flat(Infinity);
    
    
    [2,4].flatMap(x => [x,x * 2]);  相当于
    [2,4].map(x => [x,x * 2]).flat(); 对象扩展
    

    属性简洁表示法

    const a = 1;
    const b = 2;
    
    const c = {a,b};
     等同于
    const c = {a: a,b: b};
    
    const o = {
      method() {
        return "Hello!";
      }
    };
     等同于
    const o = {
      method: () {
        ;
      }
    };
    
     f(x,y) {
       {x,y};
    }
     等同于
     {x: x,y: y};
    }

    对象的扩展运算符

    let { x,...z } = { x: 1,y: 2,a: 3,b: 4 };
    x  1
    y  2
    z  { a: 3,b: 4 }
    
    let ab = { ...a,...b };
     等同于
    let ab = Object.assign({},a,b);

    Object.is()

    Object.is('str','str');  true
    Object.is({},{});  false
    +0 === -0 true
    NaN === NaN 
    Object.is(+0,-0)  false
    Object.is(NaN,NaN)  true

    Object.assign()

    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}
    • 为对象添加属性和方法
    • 克隆或合并对象
    • 给属性指定默认值

    Object.keys(),Object.values(),Object.entries()

    var obj = { foo: 'bar',baz: 42 };
    Object.keys(obj)
     ["foo","baz"]
    const obj = { foo: 'bar',1)"> };
    Object.values(obj)
     ["bar",42]
    const obj = { 100: 'a',2: 'b',7: 'c' ["b","c","a"]
    const obj = Object.create({},{p: {value: 42}});
    Object.values(obj)  []
    const obj = Object.create({},{p:
      {
        value: 42
      }
    });
    Object.values(obj)  [42]
    const obj = { foo: 'bar',1)"> };
    Object.entries(obj)
     [ ["foo","bar"],["baz",42] ]

    Object.fromEntries()

    Object.fromEntries([
      ['foo','bar'],['baz',42]
    ])
     { foo: "bar",baz: 42 }
    原创声明
    本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
    本文链接:http://www.jiecseo.com/news/show_65606.html