如何在循环中插入随机函数?

5

这有点难以解释,但我想用Javascript打印出下面的结果:

enter image description here

  • '*'字符必须是随机的。因此每次页面加载时,在我的循环内部会随机显示一个新字符。这可行吗?有人知道如何实现吗?

我已经成功生成了一个随机函数,不同的字符都在所有行中打印,并且总是在同一个位置上。我该怎么做才能确保每次只打印一个随机字符,并且在每一行中都是随机的呢?

我的代码:

const characters = '&%$*';

function generateRandomCode() {
  let result = ""
  let charactersLength = characters.length;
  for (let i = 0; i < 1; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result
}


let string = "";
for (let i = 1; i <= 5; i++) {
  for (j = 1; j <= 5; j++) {
    string += "#";
  }
  string += generateRandomCode();
  generateRandomCode();
  string += "<br>";
}

document.write(string);

这是我的代码输出的结果:

在此输入图片描述


2
在循环外创建3个随机整数,一个用于字符,一个用于行,一个用于插入字符的位置。在循环内使用这些整数。 - kiranvj
1
因此,随机数仅在循环中出现一次。 - vaira
2个回答

4

试试以下方法。我在循环外创建了3个随机整数,一个用于字符,一个用于行,一个用于插入字符的位置。在循环内使用这些整数。

const characters = '&%$*';

let string = "";
let rand = generateRandomCode(); // generate an array of 3 random numbers.

console.log(rand);

for (let i = 0; i < 5; i++) {
  for (j = 0; j < 5; j++) {
    string += rand[1] === i && rand[2] === j ? characters[rand[0]] : "#";
  }

  string += "<br>";
}

function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min)
}

function generateRandomCode() {
  return [randomIntFromInterval(0, 3), randomIntFromInterval(0, 4), randomIntFromInterval(0, 4)]
}

document.write(string);


1
这个问题并没有明确指出代码只能使用循环,只是想要创建特定的输出,并且每次加载都需要更改(至少我是这样理解的)。
所以,如果你不使用循环,也可以尝试这个选项:
  • 它首先生成了一个包含所有'#'字符的数组
  • 它选择一个随机的行、列和字符并设置它
  • 然后将其打印到html中

const characters = '&$*';
const size = 5;
// create an array with all entries
const set = new Array(size).fill().map( _ => new Array(size).fill('#') );

// choose the row based on the size of the array
const row = Math.floor( Math.random() * set.length );
// choose a column based on the size of the row selected
const col = Math.floor( Math.random() * set[row].length );
// choose a character based on the size of the string
const char = Math.floor( Math.random() * characters.length );

// overwrite the pre-existing # with the random char
set[row][col] = characters[char];

// map the rows to a string and join everything with <br />
document.querySelector('#container').innerHTML = set.map( row => row.join('') ).join('<br />');
#container {
  font-family: 'Courier New';
}
<div id="container"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接