简体   繁体   中英

JS (arrow) factory functions

For a homework problem, I need to write a function called 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,

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 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. [{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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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