繁体   English   中英

JS(箭头)工厂函数

[英]JS (arrow) factory functions

对于作业问题,我需要编写一个名为 addSquareMethod 的addSquareMethod 下面是教科书式的解决方法:

 const addSquareMethod = (arr) => {
     return arr.map(val => {
       val.square = function () {
         return this.total * this.total;
       };
       return val;
     });
   };

当我在 Google Chrome 开发工具中运行它时,它会产生以下内容,

addSquareMethod([1,2,3]);
>>>
[1, 2, 3]
0: 1
1: 2
2: 3
length: 3__proto__: Array(0)

然而,当我自己定义一个 function 时,这似乎更直观,我得到了不同的结果:

function addSquareMethod(arr){
        for (let j=0;j<arr.length;j++){
            arr[j] = arr[j]**2;
        }
        return arr;
    };

addSquareMethod([1,2,3]);
>>>
[1, 4, 9]
0: 1
1: 4
2: 9
length: 3
__proto__: Array(0)

有人可以解释教科书解决方案在做什么吗?

编辑:感谢撰写本文时的评论和回答。 我现在明白教科书定义的 function 正在寻找对象数组,而不是基元数组。 [{total:1},{total:2},{total:3}]

我已经相应地更改了体系结构,它似乎正在工作!

function addSquareMethod(arr){
        for (let j=0;j<arr.length;j++){
            arr[j].square = arr[j].total**2;
        }
        return arr;
    };

教科书的解决方案似乎很糟糕,因为它没有解释如何使用它。

教科书解决方案使用 map 为每个元素(具有数字属性“total”的对象)添加一个“square”方法/函数,包含元素“total”属性的平方值。

您的解决方案将原始数组值(数字)更改为其正方形。

使用教科书解决方案,您可以执行以下操作:

let arr = [{total:1},{total:2},{total:3}]
arr = addSquareMethod(arr)

console.log(arr[1].total) //2
console.log(arr[1].square()) //4
console.log(arr[1].total) //2 , doesnt change original value

如果您想修改您的示例以像教科书一样使用 map,您可以这样做:

const addSquareMethod = (arr) => {
     return arr.map(val => {
       return val*val;
     });
   };

let arr = [1,2,3]
console.log(arr[1]) //2
arr = addSquareMethod(arr)
console.log(arr[1]) //4

暂无
暂无

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

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