我是 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];
将数组内容作为变量中的字符串:
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的魔力
我想说的第一件事是你的语法不正确。如果您尝试表达字符串,请使用格式 -var a = "fox hen lol haha";
如果你的意思是你的变量words
是一个字符串,每个单词用空格分隔,我有解决你的问题的方法。
var words = "bla bla bla your words here";
var arrayOfWords = []; // Create the array to store words
arrayOfWords = words.split(" ");
大功告成。数组arrayOfWords
包含字符串中的所有单词作为单独的数组对象。
如果您仍然感到困惑,请在下面发表评论。
欢迎来到 Stack Overflow。
这是一种执行所需操作的方法:
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+/)
这为您省去了必须在任何地方放置引号和逗号的编辑头痛