我有一个单词列表,例如:
ventana - window
puerta - door
silla - chair
现在,我需要将其分成两个数组:
var words = ['ventana','puerta','silla'];
var defs = ['window','door','chair'];
我想我可以在换行符处拆分字符串,然后获取新数组并在每个“-”处拆分它。但我不确定具体该怎么做。有人能帮我吗?谢谢。
最佳答案
"I guess I could split the string at the line breaks, then take the new array and split that at every ' - '"
是的,如果您的意思是“获取新数组并拆分”其中的每个项目,那就可以了。假设您以这些单词作为字符串开始:
var list = 'ventana - window\npuerta - door\nsilla - chair';
然后进行如下操作:
var pairs = list.split('\n'),
words = [],
defs = [],
i, tmp;
for (i = 0; i < pairs.length; i++) {
tmp = pairs[i].split(' - ');
words.push(tmp[0]);
defs.push(tmp[1]);
}
请注意,此代码不会进行错误检查,以确保每个换行符之间的子字符串实际上确实有一对由 ' - '
分隔的单词,但我将其作为练习为你...
关于javascript - 将单词和定义列表拆分为两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19443871/