首页 > 解决方案 > 打字稿:.toString(16) - 错误预期 0 个参数,但得到 1

问题描述

我正在尝试使用 number.toString(16) 函数将数字转换为十六进制,但它给了我错误Error Expected 0 arguments, but got 1.

我的类型可能做错了,因为我相信它应该有效。

这是我的代码:

type ImageToEncode = {
  pixelsAndColors: string[][][];
  bounds: string[][][];
  paletteIndex: string;
}

task("encodeImage", "Encode an image", async function(taskArgs: ImageToEncode) {
  
  const hexPixelsAndColors = taskArgs.pixelsAndColors
  .map((array: string[][]) => {
      let firstChar = array[0].toString(16);
      let secondChar = array[1].toString(16);
      if(firstChar.length < 2) {
          firstChar = `0${firstChar}`;
      }
      if(secondChar.length < 2) {
          secondChar =`0${secondChar}`;
      }
      return [firstChar, secondChar];
  })
  .map((array: string[]) => array.join(""))
  .join("");

  const hexBounds = taskArgs.bounds.map(bound => {
    let firstChar = bound.toString(16);
    if(firstChar.length < 2) {
        firstChar = `0${firstChar}`;
    }
    return firstChar;
}).join("");

  const hexData = `0x${taskArgs.paletteIndex}${hexBounds}${hexPixelsAndColors}`
  console.log(hexData);
  return hexData;
});

因为信息可以像函数一样被解释。

标签: typescripthex

解决方案


toStringnumber.toString当你试图用字符串数组调用时,需要一个参数toString,甚至string[][]. 这是不正确的let firstChar = array[0].toString(16) // expected error

如果你想转换stringhexadecimal你应该使用parseInt(string, 10).toString(16).

例如:parseInt("100", 10).toString(16) // 64

如果你有一个字符串数组,你可以在这个函数的帮助下解析整个数组:

const toHex = (str: string) => parseInt(str, 10).toString(16)

const result = ['10', '42'].map(toHex)

推荐阅读