首页 > 解决方案 > 如何将数字转换为字母

问题描述

我有一张显示项目成本的表格。我想做而不是显示数字我想使用以下 BLACKHORSE 是 B = 1, L = 2, A = 3,C=4,K=5,H=6,7=O,8=R,9 =S 和 E=0。我如何将其放在 Google 表格中的脚本中,以在单元格 h9 中放置字母而不是数字的项目总成本的总和

标签: google-sheets

解决方案



可能有多种方法可以计算您想要的值。将此视为一种方法。


function so5715442701() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "57154427";
  var sheet = ss.getSheetByName(sheetname);

  // code to find the key for a given value in a javascript key:value array
  Object.prototype.getKey = function(value){
    for(var key in this){
    if(this[key] == value){
      return key;
    }
  }
    return null;
  };

 // a key:value array for BLACKHORSE
  var blackhorse = { 
    B : 1,
    L : 2,
    A : 3,
    C : 4,
    K : 5,
    H : 6,
    O : 7,
    R : 8,
    S : 9,
    E : 0
  };

  // get the cost value from a cell    
  var costprice = sheet.getRange("C15").getValue();

  // convert the number to a string
  var cost = costprice.toString(); // convert to string
  //Logger.log("DEBUG: cost = "+cost+", length = "+cost.length);

  // set a variable to accumulate the results
  var costtotal="";

  // loop through the characters in the cost value
  for (var i = 0; i < cost.length; i++) {
    var letter = cost.charAt(i);
    var costkey = blackhorse.getKey(letter);
    var costtotal = costtotal+costkey  
  }

  //Logger.log("DEBUG: cost = "+cost+", Blackhourse cost = "+costtotal); 
  sheet.getRange("D15").setValue(costtotal);

}

信用
-如何使用 Javascript 处理每个文本字母?
-如何通过值获取 JavaScript 对象中的键?


推荐阅读