【发布时间】:2019-07-24 14:24:43
【问题描述】:
我需要一个函数,它接收一个字符串并将等于数字的单词转换为整数。'一五七三'-> 1573
【问题讨论】:
-
你能列出一个例子吗?为什么不使用可以人性化数字的库?否则,一个简单的地图就可以解决问题。
标签: javascript arrays string arraylist
我需要一个函数,它接收一个字符串并将等于数字的单词转换为整数。'一五七三'-> 1573
【问题讨论】:
标签: javascript arrays string arraylist
这是一种方法:
const numWords = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
const changeStrToNum = str => {
let num = '';
str.split` `.forEach(numWord => {
num += numWords.indexOf(numWord);
});
return +num;
};
console.log(changeStrToNum('one five seven three'));
【讨论】:
您可以获取一个带有数字名称及其值的对象并返回一个新数字。
var words = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 },
string = 'one five seven three',
value = +string
.split(' ')
.map(w => words[w])
.join('');
console.log(value);
【讨论】:
indexOf 可能更好。
虽然它看起来与 JavaScript numbers to Words 相似,但您可以为您的用例反转此代码
发布要点和代码供参考https://gist.github.com/RichardBronosky/7848621/ab5fa3df8280f718c2e5263a7eabe004790e7e20
【讨论】:
您可以先在空间上拆分,然后使用reduce
let words = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }
let string = 'one five seven three'
let value = string
.split(' ')
.reduce((o, i) => o + words[i] ,'')
console.log(value);
【讨论】: