这是最好的方式(如果有一个)从数字转换到字符串在Typescript?
var page_number:number = 3;
window.location.hash = page_number;
在这种情况下,编译器抛出错误:
类型'number'不能赋值给类型'string'
因为位置。哈希是一个字符串。
window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function
那么哪种方法更好呢?
使用toString()或toLocaleString(),例如:
var page_number:number = 3;
window.location.hash = page_number.toLocaleString();
如果page_number为空或未定义,则抛出错误。如果你不想这样,你可以选择适合你的情况的修复:
// Fix 1:
window.location.hash = (page_number || 1).toLocaleString();
// Fix 2a:
window.location.hash = !page_number ? "1" page_number.toLocaleString();
// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toLocaleString();