【发布时间】:2019-11-19 11:46:23
【问题描述】:
首先,任何内置方法都不能使用。前任。 pop(),shift()。我可以使用的只是循环,数组等。
我想创建一个函数,它将数组作为参数并生成随机数字字符串,其中不包含数组中给出的这些数字。
例如,func([6, 2]) //=> "20353"(不会出现 2 和 6)。
数组长度可能会改变([6, 2, 9]、[7, 2, 1, 9])。所以函数必须能够容纳任意长度的数组。
为了解决这个练习题,我使用了for 和while 循环。但是,我遇到了一个问题,当检查第二个索引时(在示例中随机生成的数字是否包含 2),如果它包含,我重新生成随机数并且它可以生成第一个索引号(在这个案例,6)我不想要。
请查看我在下面发布的代码并帮助我解决这个问题。最重要的是,如果有另一种方法可以获得相同的结果,这是更好的方法,也请告诉我。
let str = "";
let arr = [];
let tem
const func = arg2 => {
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
for (let i = 0; i < arr.length; i++) {
for (let v = 0; v < arg2.length; v++) {
if (arg2[v] == arr[i]) {
do {
tem = Math.floor(Math.random() * 10);
} while (tem == arr[i])
arr[i] = tem;
}
}
}
for (let i = 0; i < arr.length; i++) str += arr[i]
return str
}
console.log(func([6, 2]))
// the output will not contain 2, which is the last index element
// however, when the second index number is removed, the output might replace it with 6, which is the first index element
预期输出:
func([6, 3, 8]) //=> "45102"
func([4, 9]) //=> "55108"
【问题讨论】:
-
字符串结果的长度应该一直是5?
-
“任何内置方法都不能使用。”:你已经在使用两个原生方法了……
标签: javascript arrays function parameters