我会解释这个函数.map()



我有一个带有.map((的函数,它是功能性的,因为我们的想法是返回一个包含元素的数组,但我不理解它的操作,如果你能解释它的开发,我会非常感谢

var number2 = [10, 20, 30];
function creatList (value) {
    
     const numbers = value.map (object => `The value is $ {object} .`);
     return numbers;
};
console.log (creatList (number2));
Result: // (3) ["The value is 10.", "The value is 20.", "The value is 30."]

Map是一个相当简单的函数,它接受列表中的每个值,并将某种函数应用于该值。在您提供的情况下,函数会将值插入字符串中。它使用的箭头函数有点不清楚,但您可以将其重写为:

const numbers = value.map (function (object) {
return `The value is $ {object} .` // This value is taken for the new list that map constructs
});

因此,作为map的另一个例子,让我们编写一个函数,将列表中的每个值乘以2。

function multListTwo(list) {
return list.map(value => value * 2); // This is shorthand for (value) => {return value * 2}
}

map函数的工作方式类似于for循环方法。它映射每一个值。

var number2 = [10, 20, 30];
function creatList (value) {
const numbers = value.map (object => `The value is $ {object} .`);
// value is [10,20,30] 10 => 0th index, 20 => 1st index, 30 is => 2nd index and length is 3.so it does 3 times mapping.
return numbers;
};
console.log (creatList (number2));

仅供参考:但是使用排列运算符是传递数组参数的最简单方法

Pablo——正如上面评论中提到的,Mozilla文档对其进行了很好的解释。话虽如此,我将尝试使用下面的另一个函数来描述它。

对于环路

const number2 = [10, 20, 30];
const numbers = [];
for (let x = 0; x < number2.length; x++) {
numbers.push(`This value is ${number2[x]}`);
};
console.log(numbers);

这有望帮助描述map((正在做什么。map((将从数组中的一个项移动到下一个项,对每个数组项执行一些函数。

因此,在您的示例代码中,幕后发生的事情是它从索引0开始。它说,"好吧,索引0处的这个值是数字10,我现在要用这个值执行一个操作。"在你的情况下,它会取这个值并将其注入字符串中。然后,它将该新值添加到新数组的索引0中。然后,它将对数组中的第二个项目执行相同的操作,然后对第三个项目执行同样的操作。对于数组中的所有项目,它都将继续。

希望能有所帮助。

最新更新