Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个 JS 函数, 功能是从数组中随机取一个元素【热度: 215】 #994

Open
yanlele opened this issue Oct 13, 2024 · 0 comments
Labels
JavaScript JavaScript 语法部分
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Oct 13, 2024

关键词:随机取数函数

以下是使用 JavaScript 实现从数组中随机取一个元素的函数:

function getRandomElement(arr) {
  if (!Array.isArray(arr) || arr.length === 0) {
    return null;
  }
  const randomIndex = Math.floor(Math.random() * arr.length);
  return arr[randomIndex];
}

你可以这样使用这个函数:

const array = [1, 2, 3, 4, 5];
const randomElement = getRandomElement(array);
console.log(randomElement);
@yanlele yanlele added the JavaScript JavaScript 语法部分 label Oct 13, 2024
@yanlele yanlele added this to the milestone Oct 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语法部分
Projects
None yet
Development

No branches or pull requests

1 participant