从JavaScript

时间:2017-12-19 21:14:15

标签: javascript string

在JavaScript中,您可以使用以下数字生成字符串:

(123).toString(36) // => "3f"

如果你试图做任意的基础:

(123).toString(40)

你得到了

Uncaught RangeError: toString() radix argument must be between 2 and 36
    at Number.toString (<anonymous>)
    at <anonymous>:1:7

想知道如何生成给定任意字母表的字符串。所以说你有这个字母:

abcdefghijklmnopqrstuvwxyz0123456789+-

那就像是:

toString(123, 'abcdefghijklmnopqrstuvwxyz0123456789+-')

它会打印出一些东西(我不知道是什么),例如3+,从字母表中挑选。

想知道如何在JavaScript中执行此操作,不确定&#34; radix&#34;与它有任何关系。谢谢。

更新:了解如何撤消它,又名fromString(string)

4 个答案:

答案 0 :(得分:1)

你可以模拟这样做:

const toString = (number, alphabet) => {
  let result = "";
  while (number) {
      const digit = number%alphabet.length;
      number = (number/alphabet.length)|0;
      result = alphabet[digit] + result;
  }
  return result || alphabet[0]; 
}

//////////////////// For the opposite, you can use this:

const fromStringBuilder = (alphabet) => {
  const alphabetKeys = {};
  for (let i = 0; i < alphabet.length; i++) {
    alphabetKeys[alphabet[i]] = i;
  }

  return (string) => {
    return [...string].reduce((a,v) => a * alphabet.length + alphabetKeys[v],0);
  }
}

//////////////////// Here you have example usage:

toAlphabet = (number) => toString(number, 'abcdefghijklmnopqrstuvwxyz0123456789+-')
fromAlphabet = fromStringBuilder('abcdefghijklmnopqrstuvwxyz0123456789+-')

console.log(fromAlphabet("3+")) // 1138
console.log(toAlphabet(1138)) // "3+"
console.log(toAlphabet(fromAlphabet("3+"))) // "3+"

注意:字母必须是至少包含两个字符的字符串。否则,循环将是无限的。

注意2:您必须以与示例相反的顺序传递字母,以获得相同的输出。

答案 1 :(得分:1)

当你要求任意长度的parseInt时,你可以使用给定的字符串并通过将前一个减少值乘以代码长度并添加代码字符位置的数值来减少它。

附加是提供的toString功能。

function parseInt(value, code) {
    return [...value].reduce((r, a) => r * code.length + code.indexOf(a), 0);
}

function toString(value, code) {
    var digit,
        radix= code.length,
        result = '';

    do {
        digit = value % radix;
        result = code[digit] + result;
        value = Math.floor(value / radix);
    } while (value)

    return result;
}

console.log(parseInt('dj', 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
console.log(toString(123, 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
console.log(parseInt('a', 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
console.log(toString(0, 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

适用于高于2的causale-multi{}基数。您只需填充any数组,而keysbase计算。

number of keys的输出为toString(123, 'abcdefghijklmnopqrstuvwxyz0123456789+-')

dj的输出为fromString('dj', 'abcdefghijklmnopqrstuvwxyz0123456789+-')

运行代码底部的代码段以查看。

这是代码:

123
// Converts a string back to it's original number form
function fromString(string, keys)
{
  var base = keys.length;
  var value = 0;
  
  if(base >= 2)
    for(var i=0; i<string.length; i++)
    {
        if(keys.indexOf(string[i]) != -1) value += keys.indexOf(string[i])*Math.pow(base,string.length - i - 1);
        else return 'Invalid code.';
    }
    return value;
}

// Converts a number from decimal base to base of keys.length
// also, it assumes you enter correct data
function toString(number, keys)
{
  var ready = false;
  var base = keys.length;
  var result = [];
  
  if(base >= 2)
    while(true)
    {
      result.unshift(keys[number % base]);
      number = Math.floor(number/base);
      if(number < 1) break;
    }
    return result.join('');
}

// Function that handles events on button click
function encryptDecrypt()
{
    var keys = document.getElementById('getTheKeys').value.split('');
    var encrypt = document.getElementById('encrypt').value;
    var encrypted = document.getElementById('encrypted');
    var decrypt = document.getElementById('decrypt').value;
    var decrypted = document.getElementById('decrypted');
    
    if(keys != '' && keys.length > 1)
    {
        if(encrypt != '' && parseInt(encrypt)) encrypted.value = toString(parseInt(encrypt), keys);
        if(decrypt != '') decrypted.value = fromString(decrypt, keys);
    }
}
.giveMeSomeSpace
{
  padding-left:47px;
}

答案 3 :(得分:0)

让基数为10的基本N的简单函数。

&#13;
&#13;
function b102bN (n,b, r = []){
  var getNumeral = d => d < 10 ? d : String.fromCharCode(d+87);
  
  return n ? (r.unshift(getNumeral(n%b)), b102bN(~~(n/b), b, r)) : r.join("");
}

console.log(b102bN(123,36));
console.log(b102bN(1453,40)); // obviously base 40 requires interesting characters as numerals
&#13;
&#13;
&#13;