简体   繁体   English

JavaScript Arrow函数语法

[英]JavaScript Arrow Function Syntax

I am studying JavaScript and have been learning how to use arrow function syntax and have come across this problem that I don't understand thoroughly and I feel this would be the best place to ask my question since I haven't found the exact answer I'm looking for on this issue, yet. 我正在学习JavaScript,并且一直在学习如何使用箭头函数语法,并且遇到了我无法完全理解的问题,并且我认为这是提出问题的最佳地点,因为我没有找到确切的答案正在寻找这个问题。 So, here is the code. 所以,这是代码。

let bigNumbers = [100, 200, 300, 400, 500];

let smallNumbers = bigNumbers.map(num => num / 100);

Now my question is, where does num come from? 现在我的问题是,num是从哪里来的? Is this a bucket to store the new values being mapped when running the code? 这是存储代码运行时存储的新值的存储桶吗? I understand that we create a new variable that will return a new array since elements from the array have been modified? 我知道我们创建了一个新变量,由于数组中的元素已被修改,该变量将返回一个新数组? I'm not quite sure, which is why I need clarification. 我不太确定,这就是为什么我需要澄清。 Thank you for your time. 感谢您的时间。

num is simply an argument of your arrow function: num只是箭头函数的一个参数:

bigNumbers.map(num => num / 100)

...is shorthand for, and functionally equivalent to: ...的简写,在功能上等同于:

bigNumbers.map((num) => {
    return num / 100;
});

In your example, using the Array map() method, the num argument is the item in the array being iterated over in that instance. 在您的示例中,使用Array map()方法, num参数是该实例中要迭代的数组中的项目。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

num is a function argument (or a Method property in your case; .map() being a Method of Array.prototype ). num是一个函数参数(或您的情况下的Method属性; .map()Array.prototype的Method)。

num ... You can name it whatever you want. num ... 您可以随意命名。

What's basic here is what it represents . 这里的基本含义什么 If you take a look at some documentation like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 如果您查看一些文档,例如https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 var new_array = arr.map(function callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg]) 

you can see that the first argument represents the currentValue , in other words the current iterating value. 您会看到第一个参数表示currentValue ,即当前的迭代值。

let smallNumbers = bigNumbers.map(num => num / 100);

which translates to 转化为

let smallNumbers = bigNumbers.map((num) => {
    return num / 100;
});

which further translates to 这进一步转化

var smallNumbers = bigNumbers.map(function(currentValue) {
    return currentValue / 100; // currentValue is the currently iterating value
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM