简体   繁体   English

JS(箭头)工厂函数

[英]JS (arrow) factory functions

For a homework problem, I need to write a function called addSquareMethod .对于作业问题,我需要编写一个名为 addSquareMethod 的addSquareMethod Below is the textbook solution:下面是教科书式的解决方法:

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

When I run this in Google Chrome dev tools, it produces the following,当我在 Google Chrome 开发工具中运行它时,它会产生以下内容,

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

However, when I defined a function on my own, that seemed more intuitive, I got a different result:然而,当我自己定义一个 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)

Can someone explain what the textbook solution is doing?有人可以解释教科书解决方案在做什么吗?

Edit: Thanks to comments and answers at time of writing this.编辑:感谢撰写本文时的评论和回答。 I understand now that the function the textbook defined is looking for an array of objects, rather than primitives.我现在明白教科书定义的 function 正在寻找对象数组,而不是基元数组。 [{total:1},{total:2},{total:3}] . [{total:1},{total:2},{total:3}]

I've changed the architecture accordingly and it seems to be working!我已经相应地更改了体系结构,它似乎正在工作!

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

The textbook solution seems bad because it doesnt explain how to use it.教科书的解决方案似乎很糟糕,因为它没有解释如何使用它。

The textbook solution uses map to add a 'square' method/function to each element (object with a number attribute 'total'), containing the square value of the 'total' attribute of the element.教科书解决方案使用 map 为每个元素(具有数字属性“total”的对象)添加一个“square”方法/函数,包含元素“total”属性的平方值。

Your solution changes the original array values (numbers) to their squares.您的解决方案将原始数组值(数字)更改为其正方形。

Using the textbook solution you can do:使用教科书解决方案,您可以执行以下操作:

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

If you wanna modify your example to use map like the textbook one, you can do it like so:如果您想修改您的示例以像教科书一样使用 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