将印度-阿拉伯数字转换为英文数字

时间:2018-07-25 16:35:24

标签: javascript arrays ecmascript-6 data-conversion template-strings

数组内部有非英文数字,​​我想将其转换为英文并将其转换为逻辑,然后对每个div执行模板字符串操作。

这是我的代码示例

const bigdata = [{img:'http://anything/com/123.png',title:'डेंजर ऑफर', inv:'१७५०'}] //Here १७५० = 1750 NOTE: I have multiple objects like this in my code

let template='';
bigdata.forEach(offers => {
function offer_tag(){
    if((HERE I WANT CONVERTED NUMBER)<15000){
       return `<span class="badge badge-warning">नवीन</span>`
    }
}

//This offer tag will be used in template string

我有一个来自jQuery的转换代码,但我非常困惑如何使用此代码将字符串数字转换为英文数字并在if语句中使用。这是jQuery代码:(我从JavaScript - replace to English number复制而来)

    var numbers = {
      '०': 0,
      '१': 1,
      '२': 2,
      '३': 3,
      '४': 4,
      '५': 5,
      '६': 6,
      '७': 7,
      '८': 8,
      '९': 9
    };

    function replaceNumbers(input) {
      var output = [];
      for (var i = 0; i < input.length; ++i) {
        if (numbers.hasOwnProperty(input[i])) {
          output.push(numbers[input[i]]);
        } else {
          output.push(input[i]);
        }
      }
      return output.join('');
    }

    document.getElementById('r').textContent = replaceNumbers('१७५०');

2 个答案:

答案 0 :(得分:1)

如果可能,您可以生成具有转换属性的新对象。

function replaceNumbers(input) {
    var numbers = { '०': '0', '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9' };
    return Array.from(input, c => numbers[c] || c).join('');
}

const
    bigdata = [{img:'http://anything/com/123.png',title:'डेंजर ऑफर', inv:'१७५०'}],
    converted = bigdata.map(o => Object.assign(...Object.entries(o).map(([k, v]) => ({ [k]: replaceNumbers(v) }))))

console.log(converted);

答案 1 :(得分:0)

您拥有的代码已经非常接近了。试试:

function parseIntHindi(text, radix){
  var numbers = { '०': 0, '१': 1, '२': 2, '३': 3, '४': 4, '५': 5, '६': 6, '७': 7, '८': 8, '९': 9 };

  function replaceNumbers(input) {
    var output = [];
    for (var i = 0; i < input.length; ++i) {
      if (numbers.hasOwnProperty(input[i])) {
        output.push(numbers[input[i]]);
      } else {
        output.push(input[i]);
      }
    }
    return output.join('');
  }

  return parseInt(replaceNumbers(text), radix)
}

console.log(parseIntHindi("१७५०"));
console.log(parseIntHindi("१७५०") +1);

相关问题