【发布时间】:2014-12-17 07:27:04
【问题描述】:
我现在有一个作业,要求我使用存储在我命名为randomNumberBetween0and5 的变量中的Math.random()(它实际上是Math.floor((Math.random() * 5) + 0);,它返回一个介于0 和5 之间的数字。我用这个数字来指代代码中其他地方的一些数组的索引。)我稍后在我的代码中再调用它两次,但我需要 Math.random() 只执行一次,然后将其值存储在 randomNumberBetween0and5 变量中以供以后使用,如果我调用而不更改变量两次或三次。
我尝试将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
【问题讨论】:
-
如果将数字存储在变量中,它将保持设置状态并且不会改变......这就是编程语言中变量的目的:保留数据。你正在用那个变量做别的事情,否则它不可能无论如何改变。
-
@MarcoBonelli
variable和keep data在同一个句子中不合适。也许constant会更合适但不太正确。 -
Math.random()在一个变量中。这意味着变量的值在每次调用时都会发生变化。我想一个常量可能不允许在Math.random()设置它之后改变值,但我几乎可以肯定 JavaScript 没有常量。 -
您对使用该变量时发生的情况的理解已关闭。创建变量时会调用
Math.random(),但不会再调用。它只是被再次调用,因为你有它在一个循环中
标签: javascript arrays math random