如何在 JavaScript 中将单词列表转换为数组

新手上路,请多包涵

我是 JavaScript 的新手。

出于学习目的,我正在尝试创建一个简单的文字输入游戏。

我只是停留在制作数组的第一步上。

那么如何将单词列表转换为数组呢?

 var words = [greet
campaign
coffee
care
revise
ridge
pilot
full
prison
wrestle
account
dictionary
start
giant
fast
monarch
patrol
bear
motif
detective
trouser
title
act
speaker
pursuit
penny
appear
ballet
agreement
welcome
similar
sensation
strong
fog
limited
implicit
nursery
neighborhood
infinite
refund
double
achievement
ample
socialist
intensify
nomination
visit
drag
retiree
mislead
situation
credit
oil
clarify
conscience
war
sow
suitcase
fixture
worth
fuss
remain
moment
frighten
spider
breathe
install
interactive
allow
deadly
cabin
restless
service
rise
integrity
artist
short circuit
perception
listen
arrangement
patience
creep
landscape
stain
citizen
microphone
nose
bullet
view
category
reign
horizon
news
social
reliable
passion
stroll
constitutional
adult
city];

原文由 RedBrick Poem 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 313
2 个回答

欢迎来到堆栈溢出。

这是一种做你想做的事情的方法:

 var words = "greet campaign coffee care revise ridge pilot full prison wrestle account dictionary start giant fast monarch patrol bear motif detective trouser title act speaker pursuit penny appear ballet agreement welcome similar sensation strong fog limited implicit nursery neighborhood infinite refund double achievement ample socialist intensify nomination visit drag retiree mislead situation credit oil clarify conscience war sow suitcase fixture worth fuss remain moment frighten spider breathe install interactive allow deadly cabin restless service rise integrity artist short circuit perception listen arrangement patience creep landscape stain citizen microphone nose bullet view category reign horizon news social reliable passion stroll constitutional adult city".split(/\s+/)

这可以让您省去在编辑时不得不在各处加上引号和逗号的麻烦

原文由 Mikkel 发布,翻译遵循 CC BY-SA 4.0 许可协议

将数组内容作为变量中的字符串,如下所示:

 var words = "greet campaign coffee care revise ridge pilot full prison wrestle account dictionary start giant fast monarch patrol bear motif detective trouser title act speaker pursuit penny appear ballet agreement welcome similar sensation strong fog limited implicit nursery neighborhood infinite refund double achievement ample socialist intensify nomination visit drag retiree mislead situation credit oil clarify conscience war sow suitcase fixture worth fuss remain moment frighten spider breathe install interactive allow deadly cabin restless service rise integrity artist short circuit perception listen arrangement patience creep landscape stain citizen microphone nose bullet view category reign horizon news social reliable passion stroll constitutional adult city";

然后,写

var wordsArray = words.split(' ');
console.log(wordsArray);

这就是 JS 的魔力

原文由 Ajay Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题