草庐IT

ES6笔记————let,箭头函数,剩余参数

枫玄雾隐 2023-04-17 原文

目录

一.let,var,const区别

let

const

区别

二,解构 

1 数组解构

2对象解构

三,箭头函数 

1 基础语法

2 省略写法

3 对象方法里的this

4 apply/call调用时的this

5 箭头函数中this

8 箭头函数应用

四,剩余函数


 

一.let,var,const区别

let

关键字用来声明块级变量。

-- 特点就是在{}声明具有块级作用域,var变量无此特点。

-- 防止循环变量编程全局变量。

-- let 关键词无变量提升。

-- let 关键词有暂时性死区的特点。{先声明后使用}

const

声明常量,常量就是值(内存地址)不能变化的量。

对象的本身是可变的,所以可以添加属性,但是地址不可改变

区别

 使用 var 声明的变量,其作用域为该语句所在的函数内,且存在变量提升现象

- 使用 let 声明的变量,其作用域为该语句所在的代码块内,不存在变量提升

- 使用 const 声明的是常量,在后面出现的代码中不能再修改该常量的值

- 使用letconst的声明的变量不属性顶层对象,返回undefined

二,解构 

1 数组解构

let [x, y, ...z] = ['a'];

x // "a"

y // undefined

z // []

let[a,...c] = [1,2,3];//合并运算符可以展开数组也可合并数组

console.log(c);//[2, 3]

console.log(...c);//2 3

let [x,y='2'] = ['a',undefined];

console.log(y);//如果没有定义,可以用默认值

说明:ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效。

2对象解构

根据key解构

let person = {name:"小帅",age:18};

let {name,age,height} = person;

console.log(name);//小帅

console.log(age);//18

console.log(height);//undefined

说明:对象的解构与数组有一个重要的不同。数组的元素是按顺序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值,否则解构失败就是undefined。

let { realname: myname,height=173 } = { realname: '张三', age: 18};

console.log(Myname);//张三

console.log(Myage)//18

console.log(realname)//realname is not defined

console.log(height)//当属性没有的时候支持默认值

说明:对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。

.3 字符串解构

let [a,b,c] = "hello";

console.log(a);//h

console.log(b);//e

console.log(c);//l

三,箭头函数 

1 基础语法

//原js写法

function myFun(k,v){   

        return k + v;

}

//es6 写法

const myFun1 = (k,v) => {

        return k+v;

}

2 省略写法

如果形参或者代码块只有一句可以简写:

Const myFun = (k) => {return k+1;} 简写:

Const myFun = k =>  k +1;

对象方法里的this

如果函数作为对象的方法调用,this指向的是这个上级对象,即调用方法的对象。

const person = {

                           name:"张三",

                           age:18,

                           say:function(){

                                  console.log(this.name);// 张三 这时候的this是person的对象

                           }

 }

person.say();

4 apply/call调用时的this

myfun1();//对象是Windows

myfun1.call(person1);//对象改变为person1

说明:两者的区别,myfun.call(person,18,29); myfun.apply(person,[18,29]);

箭头函数中this

箭头函数不绑定this关键字,箭头函数中的this,指向的是函数定义位置的上下文this。

箭头函数中的this指向是它所定义(声明)的位置,可以简单理解成,定义箭头函数中的作用域的this指向谁,它就指向谁。

const obj = { name: '张三'}

                 function fn () {

                         console.log(this);//this 指向 是obj对象

                         return () => {

                                 console.log(this);//this 指向 的是箭头函数定义的位置,那么这个箭头函数定义在fn里面,而这个fn指向是的obj对象,所以这个this也指向是obj对象

                         }

                 }

               

const resFn = fn.call(obj); //{ name: '张三'}

resFn();//{ name: '张三'}

一:全局作用域下this指向
			1:普通函数
			function global(){
				console.log(this);//window
			}
			global();
			2:箭头函数
			const global = ()=>{
				console.log(this);//window
			}
			global();
			
			
			二:对象里面的this指向
			1:普通函数
			const Person = {realname:"张三",age:19,
			   say:function(){
				   console.log(this.realname);//当前的对象 "张三"
			   }
			}
			Person.say();
			
			2:箭头函数
			const Person = {realname:"张三",age:19,
			   say:()=>{
				   console.log(this);//window
			   }
			}
			Person.say();
			
			三:构造函数的this指向
			1:普通函数
			
			function  Person(realname,age){
				this.realname = realname;
				this.age = age;
				this.say = function(){
					console.log(this);
				}
			}
			const P1 = new Person("张三",19);
			P1.say();
			
			const P2 = new Person("李四",19);
			P2.say.call(P1);//原来李四,现在是张三 call和apply改变this指向,区别传输参数的区别
			
			
			2:箭头函数
			
			function  Person(realname,age){
				this.realname = realname;
				this.age = age;
				this.say = ()=>{
					console.log(this);
				}
			}
			const P1 = new Person("张三",19); 
			P1.say();

			const P2 = new Person("李四",19);
			P2.say.call(P1);//不能改变箭头函数的this指向
			
			
			总结:普通函数与箭头函数this的区别
			1:普通的函数this与调用者有关,调用者是谁就是谁;
			2:箭头函数的this与当时定义的上下文的this有关,this是静态的一旦定义了就无法改变
			

8 箭头函数应用

练习1单击按钮2s后改变按钮文字:按钮被点击,在单击按钮改变文字:点击被取消。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<!-- 点击按钮   2s后显示:文字被点击,在点击出现文字:点击被取消。 -->
<!-- (附加:点击10次后提示“今日点击次数已上限,按钮变成灰色”) -->

<body>
    <button>点击</button>
    <script>
        let bth = document.querySelector("button")
        let flag = false
        let num=0
        bth.addEventListener("click", function () {
            flag = !flag
            num++
            if(num>10){   
                this.innerHTML="今日点击次数已上限"
                this.disabled=true
                this.style.backgroundColor="grey"
                return false
            }
            time1=setTimeout(() => { 
                if (flag) {
                    // console.log(this);
                    this.innerHTML="文字被点击"
                }
                else{
                    this.innerHTML="点击被取消"
                }
            }, 100);

        })
    </script>
</body>

</html>

四,剩余函数

剩余参数语法允许我们将一个不定数量的参数表示为一个数组,不定参数定义方式,这种方式很方便的去声明不知道参数情况下的一个函数。

1:rest参数
			function demo(...nums){
				console.log(nums);//数组
				console.log(...nums);//解构数组
			}
			demo(1,2,3);
			
			2:rest参数 对象
			function connect({username,...info}){
				console.log(username);
				console.log(info);
			}
			connect(
			   {username:"root",password:"123456",port:"3306"}
			)
			
			3:输出数组
			const arr = [1,2,3];
			console.log(...arr);
			
			4:合并两个数组
			const arr1 = [1,2,3];
			const arr2 = [4,5,6];
			console.log([...arr1,...arr2]);
			
			
			5:将类数组转为数组
			const liNode = document.querySelectorAll("li");
			console.log(typeof [...liNode]);
			
			const arr1 =  [1,2,3];
			const arr2 =  [...arr1];//复制数组
			arr1[0] = 10;
			console.log(arr2);
			
			
			6:剩余参数必须放入最后(rest参数) 不然报错
			function demo(a,b,...nums){
				console.log(nums);//数组
			}
			demo(1,2,3,4,5);

有关ES6笔记————let,箭头函数,剩余参数的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  3. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  6. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  7. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  8. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  9. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  10. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

随机推荐