javascript功能_JavaScript中的箭头功能

javascript功能

Arrow Function are short, makes a lot of sense, they are new and modern, it’s amazing and is short syntax and tactic-sugar. Arrow functions were introduced in JS ES6 (ES 2015).

箭头函数很短,很有意义,它们是新的和现代的,令人惊叹,语法和战术糖很短箭头功能在JS ES6(ES 2015)中引入。

Let’s start with a code with a traditional function to have a comparison with arrow function.

让我们从具有传统功能的代码开始,与箭头功能进行比较。

Code snippet 1

程式码片段1

const sayHello = function (name){
	return "Hey there, " + name +"!"
}
console.log (sayHello ('Sam'));

Now it’s pretty much clear what’s going in the above code snippet and the output is "Hey there, Sam!"

现在已经很清楚上面的代码片段中的内容,输出是“嘿,山姆!”

We use now arrow function to change above code.

我们现在使用箭头功能来更改上面的代码。

Code snippet 2

程式码片段2

const sayHello = (name) => "Hey there, " + name +" !"
console.log(sayHello('Sam'));

Output for both the code will be the same. Let's analyze the arrow function, as we can see that in the Code snippet 2 we do not use function keyword instead used '=>' (arrow symbol) also, we do not have any return statement but directly passed the same statement in Code snippet 2 which we passed under the return of Code snippet 1.

两个代码的输出将相同。 让我们分析箭头函数 ,因为我们可以看到在代码片段2中我们不使用function关键字,而是使用了'=>' (箭头符号),我们也没有任何return语句,而是直接在代码片段中传递了相同的语句2,我们的代码返回下通过片断1。

Syntax:

句法:

 
    (param1, param2, param3, ...) => {statement}

Where, {statement} is equivalent to => { return expression}

其中, {statement}等于=> {return expression}

Note: if statement is one line long we can omit the curly braces but the sake of clean code we prefer them and same with parenthesis if there is a single parameter then we can omit them too.

注意:如果语句只有一行,我们可以省略花括号,但是为了简洁起见,我们更喜欢花括号;如果有单个参数,则使用括号也可以,但我们也可以省略花括号。

Now let’s deal with functions with objects:

现在让我们处理带有对象的函数:

Example [Code snippet 3]:

示例[代码段3]:

const names =[{
	name: 'Sam',
	value: 0,
},{
	name: 'Tom',
	value: 1,
},{
	name: 'Max',
	value: 0,
}]

const valueZero = names.filter((name) =>name.value === 0)	//line 1

// constvalueZero = names.filter(function(name){			//line 2
//     return name.value === 0 
// })

console.log(valueZero);

Explanation:

说明:

In code snippet 3, we have an array of objects names which contains 3 names Sam, Tom, and Max with values 0, 1, 0 respectively. As we can compare the line 1 and line 2 (which are commented out) serves the same purpose but line 1 with arrow function is more concise and cleaner than the normal function in line 2 which are lengthy.

在代码片段3中 ,我们有一个对象名称数组,其中包含3个名称Sam,Tom和Max ,分别具有值0、1、0 。 正如我们可以比较的那样, 第1行第2行 (已注释掉)起着相同的作用,但是带有箭头功能的 第1行比冗长的第2行中的正常功能更简洁明了。

In line 1 (or line 2), we used a method filter() which returns elements (in our case whole object) of the array which meet a certain condition, also it requires a callback function. So in our line one, we used arrow function as our callback function.

第1行(或第2行)中 ,我们使用了filter()方法,该方法返回满足特定条件的数组元素(在我们的情况下为整个对象),还需要一个回调函数 。 因此,在第一行中,我们使用了arrow函数作为回调函数

Output:

输出:

[ { name: 'Sam', value: 0 }, { name: 'Max', value: 0 } ]

Tips – Do's and Don'ts:

提示–要做和不做:

1. Caution with THIS keyword and Arrow Function

1.注意此关键字和箭头功能

Well, so far we have seen arrow functions are so cool, easy to use and concise. So should we use arrow functions everywhere? The answer is pretty much ‘no’. What I mean let me demonstrate it with this keyword in following example [Code snippet 4]:

好吧,到目前为止,我们已经看到箭头功能非常酷,易于使用和简洁。 那么我们应该在所有地方使用箭头功能吗? 答案几乎是“不”。 我的意思是让我在以下示例[代码片段4]中使用此关键字进行演示:

Example [Code snippet 4]

示例[代码段4]

let javascript = {
	totalArticles: 105,
	totalContentWriter: 3,
	description1:() => {
		return `IncludeHelp have ${this.totalArticles} articles on JavaScript provided by 
		${this.totalContentWriter} content writers`
	},
	description2: function() {
		return `IncludeHelp have ${this.totalArticles} articles on JavaScript provided by 
		${this.totalContentWriter} content writers`
	}
}
console.log(`Description2: ${javascript.description2()}`);
console.log(`Description1: ${javascript.description1()}`);


Output

输出量

Arrow function JS code output 1

Explanation:

说明:

Now we created an object named javascript which contain about the total number of articles and content writer contributed for it on IncludeHelp.com (It is a hypothetical data, not real). So we created two functions, out of one is an arrow function. Now we make both description1 and description2 similar but in the output, arrow function returned undefined while the required output was returned with normal function. This is because of this keywordarrow function nothing is bind neither the arguments nor this so they are completely free, thus we need to explicitly bind it if we really want to use it in this manner.

现在,我们创建了一个名为javascript的对象,该对象包含IncludeHelp.com上的文章总数和内容编写者对此的贡献(这是假设数据,不是真实数据)。 因此,我们创建了两个函数,其中一个是箭头函数 。 现在,我们使description1和description2相似,但是在输出中, 箭头函数返回未定义状态,而所需的输出通过普通函数返回。 这是因为此 keywordarrow函数不会绑定任何参数,也不会绑定任何参数,因此它们是完全免费的,因此,如果我们确实想以这种方式使用它,则需要显式绑定它。

2. Never use arrow Functions with methods or constructors

2.切勿将箭头函数与方法或构造函数一起使用

There can be use case scenario but most of the times people like to avoid them.

可能存在用例场景,但是大多数时候人们喜欢避免使用它们。

3. In Redux

3.在Redux中

There is one thing we do in Redux is returning back a lot of key-value pairs and using the arrow function we can use it, but here is a word of caution.

Redux中我们要做的一件事是返回很多键值对,并使用arrow函数可以使用它,但这是一个警告。

Example:

例:

    const func = () => {key: 'value'}    
    //output : undefined

If you do something like that you’ll be getting undefined. So right way is:

如果执行类似的操作,则将变得不确定。 所以正确的方法是

    const func = () => ({key: 'value'})		
    //output : {key: 'value'}


翻译自: https://www.includehelp.com/code-snippets/arrow-function-in-javascript.aspx

javascript功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值