Home > front end >  define an arrey just once and change that without defining again in javascript
define an arrey just once and change that without defining again in javascript

Time:03-16

//Hello
//I want to define an array in a line of the program, for example, as follows
var a = [2,5];
//In the next steps, I want to increase the array elements as follows:
a[0]  = 2;
a[1]  = 2;
//And I want the array to increase intermittently at the output of the program, as follows:
a = [4,7]
a = [6,9]
a = [8,11]
....

// But in reality this does not happen because in the first line of the program, the array is //defined again and again //And the output is always as follows: a = [4,7] // Is there a way to initialize the a array as [2,5] only once????

CodePudding user response:

There are many ways to do this.

  • This is a very simple way if you want to increase it a fixed number of times:
    let a = [2,5];
    for (let i=0;i<5;i  ) {
        a=a.map(element=>element 2);
        console.log(a);
    }
    function * arrayIncreaser(initialArray, num) {
      let a = initialArray;
      while (true) {
        a = a.map(element=>element num)
        yield a;
      }
    }
    
    const increaser = arrayIncreaser([2,5],2)
    console.log(increaser.next().value);
    console.log(increaser.next().value);
    console.log(increaser.next().value);

CodePudding user response:

Here, I use a closure. The array is created once and modified each time you call increase():

function createIncreaseFunction()
{
  const a = [2,5];
  function increase()
  {
    a[0]  = 2;
    a[1]  = 2;
    return a;
  }
  return increase;
}
let increase = createIncreaseFunction();
console.log(increase()); // [4,7]
console.log(increase()); // [6,9]
console.log(increase()); // [8,11]

// increase() modifies the values in the array,
// but the same array is returned each time:
console.log(increase() === increase()); // true

  • Related