我現在有一項任務,它要求我使用Math.random()
保存在一個變量中,我已經命名爲randomNumberBetween0and5
(它實際上是Math.floor((Math.random() * 5) + 0);
,它返回一個介於0和5之間的數字。我使用這個數字來指代其他地方某些數組的索引)我在代碼中多次調用它兩次,但是我需要Math.random()
只執行一次,然後將它的值存儲在randomNumberBetween0and5
變量中以備後用,而不會更改,如果我再次調用變量兩次或三次。我怎麼能讓Math.random()在每次調用存儲在其中的變量時都返回不同的值?
我試圖將randomNumberBetween0and5
的值存儲在另一個變量中,並且(如預期的那樣)並不能幫助解決問題。任何幫助肯定會感激!謝謝!
(這裏的一切都只是在案件的代碼,你想看到它。)
var names = ["Lázaro", "Aviram", "Samuel", "Miles", "Felix"]; // Defining an array of random names
var people = []; // Declaring the array to hold each instance of the 'Person' object
// For() to create one new instance thrice for three names of the 'names' array in the 'Person' object defined in 'person.js'
for (var i=0;i < 3;i++) {
var randomNumberBetween0and5 = Math.floor((Math.random() * 5) + 0); // Randomly choosing a number for the arrays to be passed to the 'Person()' object's methods defined in 'person.js'
var newInstance = new Person.generate(names.splice(randomNumberBetween0and5,randomNumberBetween0and5+1),Person.actions[randomNumberBetween0and5],Person.jobs[randomNumberBetween0and5],i+1); // Creating a new instance of the 'Person()' object and passing a random name, action (from the Person object's properties), and job (also from the Person object's properties), along with the current loop number for the row to use (i begins at 0 so it becomes 1,2,3 instead of 0,1,2 when a 1 is added)
//people.push(newInstance); // Adding the new instance to the 'people' array of instances
people.push(newInstance); // Adding the newly created instance of 'Person' to the variable 'people'
}; // Ending the for()
console.log(people); // Logging the 'people' array for debugging
console.log("Main.js has been completely interpreted -- Nothing has broken yet."); // Reassuring console log to state that this file has completely executed without breaking
如果將數字存儲在變量中,它將保持設置狀態,並且不會更改...這是編程語言中變量的用途:保留數據。你對這個變量做了其他的事情,否則它不可能發生變化。 – 2014-10-21 22:27:32
@MarcoBonelli'variable'和'keep data'在同一個句子中不適合。也許'不變'會更合適但不完全正確。 – silentw 2014-10-21 22:28:48
'Math.random()'在一個變量中。這意味着變量的值每次調用都會發生變化。我想在'Math.random()'設置它後,常量可能不允許改變值,但我幾乎可以確定JavaScript沒有常量。 – 2014-10-21 22:31:41