我现在有一项任务,它要求我使用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