需要来自 for 循环的多个值

问题描述 投票:0回答:2

我想重复 for 循环,每次都给我们带来新的价值。 每当我运行 for 循环时,我应该得到不同的值。 请解决我的问题

let hex = 'ABCDEF0123456789';
let res = '';
for (let i = 1; i <= 6; i++) {
    res += hex.charAt(Math.floor(Math.random() * hex.length));
    // console.log(i);
} 

每次调用或运行 for 循环时,我都想获取新值。 例如 - 如果我多次打印 res 的值。每次 我想要不同的价值

javascript for-loop random repeat
2个回答
1
投票

你的意思是你想把你的代码放在一个函数中并调用这个函数吗?

function res() {
  let hex = 'ABCDEF0123456789';
  let res = '';
  for (let i = 1; i <= 6; i++) {
    res += hex.charAt(Math.floor(Math.random() * hex.length));
  }
  return res;
}

console.log(res()) // => one value
console.log(res()) // => another value
console.log(res()) // => a third value

0
投票
let hex = 'ABCDEF0123456789';
let res = '';
for (let i = 1; i <= 6; i++) {
  res = hex[Math.floor(Math.random() * hex.length)];
  console.log(res);
};
© www.soinside.com 2019 - 2024. All rights reserved.