【这是我参与更文挑战的第 13 天,活动详情查看: 更文挑战”】
变量的声明和箭头函数
let
let 主要定义在代码块中,形成一个块级作用域,让该变量只能在只能在该作用域下使用。
{
a = 10
console.log(a); // 10
}
console.log(a); //a is defined
const
使用const声明的变量是无法被更改的,如果意外修改 则报错 xx has already been declared
const a = 10
let a = 11 //'a' has already been declared
箭头函数和普通函数
普通函数的this指向的是 他的调用者,默认为window。
严格模式下 未调用的函数指向为undefined
箭头函数
箭头函数没有this,他的this是继承自他的父级元素,默认的指向为所处的位置的父级元素的this。
//普通函数
function a() {
console.log(this); // Window
}
a()
a是一个全局函数 挂载于window下面 这种写法其实和window.a是一样的, 如果我们在控制台输入 window.a则会直接打印出 我们写的 这个函数。
let fn = {
fun:function a() {
console.log(this);
},
}
fn.fun()
//此时的this是fn这个对象。
那么我们将代码简单的改一下
let fn = {
fun: () => {
console.log(this);
}
}
fn.fun()
//Window
由于 他的父级并没有this 所以 指向为 Window
let fn = {
fun: function a() {
let f1 = () => {
console.log(this); //{fun: ƒ}
};
f1();
},
};
fn.fun();
看一下上面这个 我先调用了fun方法 在 fun方法里面有调了f1箭头函数,那么 他就会把父元素的this 拿过来。.
默认传参
function a (a, b=34, c=12){
console.log(a, b, c);
}
a(12, 56, 67) //12, 56, 67
a(13) //13, 34, 12
方法
for of 循环
for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
//请看下面代码
const array1 = ['a', 'b', 'c'];
for (const item of array1) {
console.log(item); //"a", "b", "c"
}
//map
const arr2 = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (item of arr2){
console.log(item); // ["a", 1],["b", 2],["c", 3]
}
//如果 你先得到某一个单项值的话 可以这样
for (let [key, value] of arr2) {
console.log(value); //1, 2, 3
console.log(value); //a, b, c
}
Array.from()
Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。