Skip to content

搞英语 → 看世界

翻译英文优质信息和名人推特

Menu
  • 首页
  • 作者列表
  • 独立博客
  • 专业媒体
  • 名人推特
  • 邮件列表
  • 关于本站
Menu

使用 JavaScript 获取随机数组项

Posted on 2022-05-09

JavaScript 数组可能是我最喜欢的 JavaScript 原语。你可以用数组做各种很棒的事情:获取唯一值、克隆它们、清空它们等。从数组中获取随机值怎么样?

要从数组中获取随机项,您可以使用Math.random :

  
常量 arr = [  
    “一”,  
    “二”,  
    “三”,  
    “四”,  
    “告诉”,  
    “我”,  
    “那”,  
    “你”,  
    “爱”,  
    “我”,  
    “更多的”  
];  
const random1 = arr[(Math.floor(Math.random() * (arr.length)))]  
const random2 = arr[(Math.floor(Math.random() * (arr.length)))]  
const random3 = arr[(Math.floor(Math.random() * (arr.length)))]  
const random4 = arr[(Math.floor(Math.random() * (arr.length)))]  
  
控制台日志(随机 1,随机 2,随机 3,随机 4)  
// 再告诉一个两个  

至于何时需要数组中的随机值取决于您的个人应用程序。但是,很高兴知道您可以轻松获得随机值。 Array.prototype.random应该存在吗?

使用 JavaScript 获取随机数组项的帖子首先出现在David Walsh 博客上。

原文: https://davidwalsh.name/javascript-random-array

本站文章系自动翻译,站长会周期检查,如果有不当内容,请点此留言,非常感谢。
  • Abhinav
  • Abigail Pain
  • Adam Fortuna
  • Alberto Gallego
  • Alex Wlchan
  • Answer.AI
  • Arne Bahlo
  • Ben Carlson
  • Ben Kuhn
  • Bert Hubert
  • Bits about Money
  • Brian Krebs
  • ByteByteGo
  • Chip Huyen
  • Chips and Cheese
  • Cool Infographics
  • Dan Sinker
  • David Walsh
  • Dmitry Dolzhenko
  • Elad Gil
  • Ellie Huxtable
  • Ethan Marcotte
  • Exponential View
  • FAIL Blog
  • Founder Weekly
  • Geoffrey Huntley
  • Geoffrey Litt
  • Greg Mankiw
  • Henrique Dias
  • Hypercritical
  • IEEE Spectrum
  • Investment Talk
  • Jaz
  • Jeff Geerling
  • Jonas Hietala
  • Josh Comeau
  • Lenny Rachitsky
  • Lou Plummer
  • Matt Stoller
  • Mert Bulan
  • Mostly metrics
  • News Letter
  • NextDraft
  • Non_Interactive
  • Not Boring
  • One Useful Thing
  • Phil Eaton
  • Product Market Fit
  • Readwise
  • ReedyBear
  • Robert Heaton
  • Ruben Schade
  • Sage Economics
  • Sam Altman
  • selfh.st
  • Shtetl-Optimized
  • Simon schreibt
  • Slashdot
  • Small Good Things
  • Taylor Troesh
  • Telegram Blog
  • The Macro Compass
  • The Pomp Letter
  • Thinking Deep & Wide
  • Tim Kellogg
  • 英文媒体
  • 英文推特
  • 英文独立博客
©2025 搞英语 → 看世界 | Design: Newspaperly WordPress Theme