JavaScript基础练习题(五)

发布时间:2023年12月29日
  1. 生成一个范围内的随机整数:编写一个函数,接收两个参数,表示范围的最小值和最大值,然后生成一个在这个范围内的随机整数。

  2. 生成指定长度的随机字符串:编写一个函数,接收一个参数表示字符串的长度,然后生成一个指定长度的随机字符串,可以包含字母和数字。

  3. 随机打乱数组元素的顺序:给定一个包含多个元素的数组,编写一个函数,能够随机打乱数组中元素的顺序,使得每次打乱结果都是随机的。

  4. 生成随机颜色:编写一个函数,生成一个随机的RGB颜色值,确保每次生成的颜色都是随机的。

  5. 随机选择数组中的元素:给定一个包含多个元素的数组,编写一个函数,能够随机选择一个数组中的元素,并将其返回。

代码如下:

当然,以下是每道练习题的具体代码和注释:

  1. 生成一个范围内的随机整数:
function getRandomInteger(min, max) {
  // 计算范围内的整数个数(包括 min 和 max)
  const count = max - min + 1;
  // 生成一个随机数,范围在 [0, count) 之间
  const random = Math.floor(Math.random() * count);
  // 将随机数与 min 相加,得到最终的随机整数
  return random + min;
}

const randomInt = getRandomInteger(1, 10);
console.log(randomInt);

  1. 生成指定长度的随机字符串:
function getRandomString(length) {
  const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let randomString = '';

  for (let i = 0; i < length; i++) {
    // 生成一个随机的索引,范围在 [0, characters.length) 之间
    const randomIndex = Math.floor(Math.random() * characters.length);
    // 根据随机索引获取字符,并追加到随机字符串中
    randomString += characters.charAt(randomIndex);
  }

  return randomString;
}

const randomStr = getRandomString(6);
console.log(randomStr);

  1. 随机打乱数组元素的顺序:
function shuffleArray(array) {
  const shuffledArray = array.slice(); // 复制数组,避免修改原始数组
  for (let i = shuffledArray.length - 1; i > 0; i--) {
    // 生成一个随机的索引,范围在 [0, i+1) 之间
    const randomIndex = Math.floor(Math.random() * (i + 1));
    // 将当前位置的元素与随机位置的元素交换
    [shuffledArray[i], shuffledArray[randomIndex]] = [shuffledArray[randomIndex], shuffledArray[i]];
  }
  return shuffledArray;
}

const originalArray = [1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(originalArray);
console.log(shuffledArray);

  1. 生成随机颜色:
function getRandomColor() {
  // 生成红、绿、蓝三个通道的随机颜色分量,取值范围在 [0, 255] 之间
  const red = Math.floor(Math.random() * 256);
  const green = Math.floor(Math.random() * 256);
  const blue = Math.floor(Math.random() * 256);
  // 将颜色分量以 RGB 格式拼接,并返回最终的随机颜色值
  return `rgb(${red}, ${green}, ${blue})`;
}

const randomColor = getRandomColor();
console.log(randomColor);

  1. 随机选择数组中的元素:
function getRandomElement(array) {
  // 生成一个随机的索引,范围在 [0, array.length) 之间
  const randomIndex = Math.floor(Math.random() * array.length);
  // 返回随机索引对应的元素
  return array[randomIndex];
}

const array = [1, 2, 3, 4, 5];
const randomElement = getRandomElement(array);
console.log(randomElement);

希望以上代码和注释能够帮助你更好地理解和应用随机数生成的相关概念和技巧。

文章来源:https://blog.csdn.net/weixin_70007095/article/details/135294856
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。