WishMeLz

生活其实很有趣

JS罗马数字转整数

  let obj = {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000
  }

  function fn(v) {
    let res = 0;
    for (var i = 0; i < v.length; i++) {
      let front = v[i];
      let back = v[i + 1];
      if (obj[back] > obj[front]) {
        res -= obj[front]
      } else {
        res += obj[front]
      }
    }
    return res;
  }

  console.log(fn("MCXCIV"));