简体   繁体   中英

How can I create an array of user-provided numbers and map that to an array of the numbers' cubes?

My application is having a user supply a set of numbers. The user determines how many numbers they will provide, and then I prompt them accordingly. I want to create an array of the provided input numbers using a function. Then I want to use another function to calculate the cube of each of these numbers, and put those in a new array. I am finding it difficult to create the array of cubes. Can anyone help me with this?

 var BR = "<br />"; var ES = " "; /********* FUNCTIONS *********/ // Enter any functions in this region function fncube(c) { var result = 1; var tro; for (var j = 0; j < c.length; j++) { result = c[j] * c[j] * c[j]; tro = new Array(result); } return tro; } function displayarray(d) { var mm = new Array(); for (var m = 1; m < d.length; m++) { mm = mm.push[m]; } return mm; } /********* MAIN *********/ function main() { var userinput = new Array(); //var m = new Array(); var usersize; var tilavg; usersize = parseInt(window.prompt("Enter number of cubes you would like to make: ")); for (var i = 0; i < usersize; i++) { userinput[i] = parseInt(window.prompt("Enter your number #: " + (i + 1))); document.writeln(BR + "Number you entered " + " for making cube is : " + userinput[i] + ES) document.writeln(BR + "The cube is " + fncube(userinput) + ES); var cc = fncube(userinput); xx = new Array(cc); //var z = displayarray(cc); } document.writeln(BR + "The array of input values is: " + cc); document.writeln(BR + "The array of cubes is: " + xx); } main(); 

The JavaScript Array map method natively supports transforming an array to another array of the same size where the translation function is the same for each element. If you define your transformation function as the cubing operation (in JS that's Math.pow(x, 3) ), then you can easily translate from one array to another.

Consider the example below. I use jQuery's version of map to transform input elements to an array of their values, then use the JS map method to transform that array to an array containing the cubes of all the values. Give it a try. You should be able to tweak this to fit your use-case once you understand how map works.

 $(function() { $("input").change(function() { var nums = $("input").map(function() { return this.value || undefined; }).get(); $("#nums").text(nums); $("#cubes").text(nums.map(function(i) { return Math.pow(i, 3); })); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h4>Enter four numbers</h4> <input /><br /> <input /><br /> <input /><br /> <input /> <div id="nums"></div> <div id="cubes"></div> 

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