简体   繁体   中英

JavaScript function that produces an array that multiplies x number of times based on previous integer

So I've got this function and it needs to produce an array that multiplies x number of times based on previous integer. The function would take two integers as arguments as so:

function powerOf(x, n) {

}

For example: powerOf(3, 4) will produce [3, 9, 81, 6561].

Can someone point me in the right direction?

Here's a clean solution:

 function powerOf(x, n) { var res = [x]; for(var c=1; c<n; c++) { res.push(x *= x); } return res; } alert(powerOf(3, 4)); 

function powerOf(x, n){
  // First, create a results array to store your results in.
  var resultsArr = [];

  // Then create a variable to store your number.

  var num;

  // Iterate from 1 to n.
  for (var i = 1; i <= n; i++) {
    // If num is not yet defined, set it to x and push it to the array
    if (!num) {
      num = x;
      resultsArr.push(num);
    } else {
      // Otherwise, set num to num squared and push that to the array.
      num = Math.pow(num, 2);
      resultsArr.push(num);
    }
  }

  // Return the results array.
  return resultsArr;
}

This is the function you've been looking for:

function test(a,b){
    // declarin array for result
    var res = [a];

    // going through array and adding multiplied numbers
    for(var i = 1; i<b;i++){
        res[i] = res[i-1]*res[i-1];
    }

    // returning the result
    return res;
}

console.log(test(3,4)); // result : [3, 9, 81, 6561]

First you decalare array that will server you as result.First entry in array is your first number (a). Now for rest of array (b-1), you need to multiply last entry in array with it self.

var powerOf = function (x, n) {
    //create an array to store values
    var array = [];
   //loop through values and push them to the array
   for (var i = 1; i < n; i++) {
       array.push(x *= x);
   }

   //return array
   return array;
};

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