0

I'm trying to create 20 functions stored in variables. Each one adds a specific amount of numbers to another quantity. Here's an example:

function creaSuma(x){
    return function(y){
        return x + y;
    }
}

for(let i=1; i<21; i++){
    add+1=creaSuma(i); //this doesn't work. How would you change it?
}

In this case:

console.log(add15(10));

the output should be 25

So, how would I create those 20 variables without creating an array? (I tried it and it works) Thank you, it is just out of curiosity.

2 Answers2

0

try the following

function creaSuma(x){
    return function(y){
        return x + y;
    }
}

for(let i=1; i<21; i++){
    window['add' + i] = creaSuma(i); //this doesn't work. How would you change it?
}
console.log(add15(10));

will output 25

I'm using window for dynamic variable namings, as it has a reference to all global variables and global functions you are using.

You can alternatively use the same approach but with a custom object.

Basel Issmail
  • 3,847
  • 7
  • 20
  • 36
0

As I mentioned in the comment to the original post, use an object and let these be dynamic properties/fields of the object.

Here is your modified code:

function creaSuma(x) {
    return function (y) {
        return x + y;
    }
}
var x = function () {

}
for (let i = 1; i < 21; i++) {
    x['add' + i] = creaSuma(i); //this doesn't work. How would you change it?
}

console.log(x.add15(10));
fiveelements
  • 3,649
  • 1
  • 17
  • 16