How to execute a cube of numbers of a given array in JavaScript?


To find the cubes of elements of given array we need to run a for loop to access each and every element and we need to use "=" operator to replace elements with their cubes.To get the desired values the below steps need to be followed.

Steps

1) Declared an array a = [1,2,3,4,5]

2) For loop was introduced to access each and every element in the array(a[i]).

3) Inside for loop "=" operator is used to replace the element with their cubic values(a[i]*a[i]*a[i]).

so, from the above steps the output obtained will be 1,8,27,64,125.By following the above steps we can get not only cubes but also any power of elements in a provided array.

Example

Live Demo

<html>
<body>
<script>
   var a = [1,2,3,4,5];
   for ( var i = 0; i < a.length;i++) {
      a[i] = a[i]*a[i]*a[i];
   }
   document.write(a);
</script>
</body>
</html>

Output

[1, 8, 27, 64, 125]

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements