【发布时间】:2020-11-24 17:19:30
【问题描述】:
我是编码新手,大约一周前开始使用诸如 Mark Myers 题为“学习 Javascript 的更智能方法”的书和在线教程等资源。我想尝试一些东西,但到目前为止没有成功。
简而言之,我想从三个数组开始。其中两个将有三个值,第三个最初是一个空数组。我希望将第一个数组的每个值与第二个数组的每个值连接起来,并将结果添加到第三个(最初为空)数组中。由于第一个数组和第二个数组各包含三个值,因此一共有九种组合,从而在第三个数组中产生九个值。
我想要实现的是为第一个数组的每个值显示可能的三个组合中的一个。我希望这以随机的方式发生,使用上述书籍已经涵盖的陈述,我已经知道的陈述,而不是徘徊在未知领域。
我的方法是创建三个随机数,每个随机数代表第三个数组中的一个值(更准确地说是索引),该数组将容纳第一个和第二个数组的组合(连接)。因此,我希望第一个随机数为 0、1 或 2 以“选择”第一个数组的第一个值的可能组合,第二个随机数为 3、4 或 5 以选择可能的组合第一个数组的第二个值,最后是第三个随机数,6、7 或 8 指向第一个数组的第三个值的组合。
目标是在控制台中记录随机选择的组合(连接) - 第一个数组的每个值对应一个。换句话说,我希望在日志中看到三个串联。但是,控制台只返回一个连接。
有人可以解释一下到底缺少什么或错误吗?我相信我的代码中的问题在于最后一行,但到目前为止无法弄清楚问题到底是什么。我也不确定为什么 Visual Studio Code(我使用的是“Prettier”扩展名)会修改我的最后一行的格式
console.log(strNum[num1, num2, num3]);
到
console.log(strNum[(num1, num2, num3)]);
保存文件后,但这可能与我的问题无关。
我的代码如下:
// Declaring variables for the operation
var str = ["a ", "b ", "c "]; // Array str to hold strings a, b and c
var num = ["1", "2", "3"]; // Array num to hold numbers 1, 2 and 3
var strNum = []; // Array strNum to hold all possible combinations of array str and array num
var k = 0; //Counter for array strNum
// Combining the contents of array str and array num and adding the combinations to array strNum
for (i = 0; i < str.length; i++) {
for (j = 0; j < num.length; j++) {
strNum[k] = str[i] + num[j];
k++;
}
}
// The first random number between with the possible values 0, 1 or 2, to determine the first pair
var bigDecimal1 = Math.random();
var improvedDecimal1 = bigDecimal1 * 3;
var RandomNum1 = Math.floor(improvedDecimal1);
// The second random number between with the possible values 3, 4 or 5, to determine the second pair
var bigDecimal2 = Math.random();
var improvedDecimal2 = bigDecimal2 * 3 + 3;
var randomNum2 = Math.floor(improvedDecimal2);
// The third - and last - random number between with the possible values 6, 7 or 8, to determine the third pair
var bigDecimal3 = Math.random();
var improvedDecimal3 = bigDecimal3 * 3 + 6;
var randomNum3 = Math.floor(improvedDecimal3);
console.log(strNum[(num1, num2, num3)]);
【问题讨论】:
-
不是 100% 清楚,但这是您想要的吗?
console.log([strNum[RandomNum1], strNum[randomNum2], strNum[randomNum3]]); -
哦,是的!这正是我想要的!我想我可以简单地一个接一个地“列出”三个随机数。我还注意到我在代码的最后一行错误地命名了我的随机数(它们的名称与声明的变量名称不同,事实上,我之前重命名变量时忘记重命名它们)。您的解决方案与我想象的完全一样。谢谢!
标签: javascript arrays logging random