typescript - 打字稿:.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;
});
因为信息可以像函数一样被解释。
解决方案
toString
number.toString
当你试图用字符串数组调用时,需要一个参数toString
,甚至string[][]
. 这是不正确的let firstChar = array[0].toString(16) // expected error
。
如果你想转换string
成hexadecimal
你应该使用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)
推荐阅读
- python - Python npy文件如何访问变量
- sql - SQL如何不插入重复值
- javascript - Chrome 扩展:将变量(url)发送到 python
- wordpress - 导入后wordpress用户配置文件url问题
- ios - 呼叫 Btn 给出错误的号码
- html - Angular 反应式表单验证
- javascript - 如何使用扩展获取 Azure Notebook 的用户详细信息?
- zsh - 通过 cmder 或 conemu 在 wsl 上运行 zsh 时,光标键在 vim 中不起作用
- android - 升级到 Android Studio 3.2.1 后出现构建错误
- android - Android WiFi-Direct 组队