我需要一个函数,该函数需要一个字符串并将等于数字的单词转换为整数。'一五七三'-> 1573
答案 0 :(得分:3)
这里是一种方法:
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'));
答案 1 :(得分:2)
您可以使用带有数字名称及其值的对象,然后返回一个新数字。
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);
答案 2 :(得分:0)
虽然看上去与JavaScript numbers to Words类似,但您可以针对自己的用例反转此代码
发布要点与参考https://gist.github.com/RichardBronosky/7848621/ab5fa3df8280f718c2e5263a7eabe004790e7e20的代码
答案 3 :(得分:0)
您可以先在空间上拆分,然后再使用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);