栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用JavaScript的罗马数字翻译器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用JavaScript的罗马数字翻译器

错误的主要根源是,我定义的reduce方法不允许我在迭代时访问索引。我更新了我的reduce函数,然后经过一点调试就可以了:

var DIGIT_VALUES = {  I: 1,  V: 5,  X: 10,  L: 50,  C: 100,  D: 500,  M: 1000};var each = function(collection, iterator) {  if (Array.isArray(collection)) {    for (var i = 0; i < collection.length; i++) {      iterator(collection[i], i, collection);    }  } else {    for (var key in collection) {      iterator(collection[key], key, collection);    }  }};var reduce = function(collection, iterator, total) {  if (total == undefined) {    total = collection.shift();  }  each(collection, function(val, i) {    total = iterator(total, val, i);  })  return total;};var translateRomanNumeral = function(roman) {  if (typeof(roman) !== 'string') {    return null;  }  if (!roman) {    return 0;  }  // if it's not in the digit values object, return null  for (var i = 0; i < roman.length; i++) {    if (!(roman[i] in DIGIT_VALUES)) {      return null;    }  }  //with underscore:  return reduce(roman, function(memo, letter, i) {    var num = DIGIT_VALUES[letter];     //console.log(i);    //how do you acess the next item in a collection in reduce?    var next = DIGIT_VALUES[roman[Number(i) + 1]];    // console.log(Number(i) + 1);    // console.log(next);      if ( next === undefined || next <= num) {        return memo + num;        //console.log(memo);      }      else {        // var diff = num - prev;        // console.log(diff);        return memo - num;        // memo = memo + (next - num);      }    // return memo;  }, 0);};console.log(translateRomanNumeral("LXIV")); //returns 66 ---> should return 64console.log(translateRomanNumeral("IX")) // should return 9console.log(translateRomanNumeral("IV")) /// should return 4console.log(translateRomanNumeral("CI")); //working --> returns 101console.log(translateRomanNumeral("MMMMCCL")); // working ---> returns 4250.//works!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616997.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号