JS(箭头)工厂函数

问题描述 投票:0回答:1

对于家庭作业问题,我需要编写一个名为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 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)

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

编辑:感谢撰写本文时的评论和答案。我现在知道,教科书定义的功能正在寻找对象数组,而不是基元。 [{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;
    };
javascript methods properties
1个回答
1
投票

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

[教科书解决方案使用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

如果您想修改示例以像地图一样使用地图,则可以这样做:

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
© www.soinside.com 2019 - 2024. All rights reserved.