【问题标题】:How to turn words into whole numbers如何将单词变成整数
【发布时间】:2019-07-24 14:24:43
【问题描述】:

我需要一个函数,它接收一个字符串并将等于数字的单词转换为整数。'一五七三'-> 1573

【问题讨论】:

  • 你能列出一个例子吗?为什么不使用可以人性化数字的库?否则,一个简单的地图就可以解决问题。

标签: javascript arrays string arraylist


【解决方案1】:

这是一种方法:

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'));

【讨论】:

    【解决方案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);

    【讨论】:

    • 赞成你的,因为在我的回答中,在对象文字上使用 O(1) 查找比在数组上使用 indexOf 可能更好。
    【解决方案3】:

    虽然它看起来与 JavaScript numbers to Words 相似,但您可以为您的用例反转此代码

    发布要点和代码供参考https://gist.github.com/RichardBronosky/7848621/ab5fa3df8280f718c2e5263a7eabe004790e7e20

    【讨论】:

    • 如果它是一个骗子,那么标记它。但事实并非如此,OP 正在寻找逆运算。
    • 感谢您的通知。
    【解决方案4】:

    您可以先在空间上拆分,然后使用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);

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多