根据另一个变量的数据类型转换一个变量
Cast a variable based on the data type of another variable
我想要一个基于“引用”类型变量转换变量的函数。
我猜该函数将采用两个参数 cast(x, ref)
,其中 x
是根据 ref
的数据类型转换的变量。
例如:
let myVar = cast(3, "helloworld");
console.log(myVar); // "3"
let myNewVar = cast(myVar, 32423n);
console.log(myNewVar); // 3n
现在,如果 ref
是 bigint
,我只能将数字转换为 bigint
const cast = (n, ref) => typeof ref === "number" ? n : BigInt(n)
最好将一个变量转换为另一个变量的数据类型。
// Cast will attempt to force cast something (n) into the type of
// something else (ref)
const cast = (n, ref) => {
switch(typeof(ref)) // All major types and how to convert them
{
case "boolean": return Boolean(n);
case "number": return Number(n);
case "bigint": return BigInt(n);
case "string": return String(n);
case "symbol": return Symbol(n);
case "undefined": return undefined;
default: return n; // If none of the above is the type, we return n
}
}
// Example: 2 is an int, and the reference is a string, so we cast an int
// to a string, this could be done with various types more complexly
let a = 2
let b = "hello"
a = cast(a, b)
console.log(a, typeof(a)) // 2, string
我想要一个基于“引用”类型变量转换变量的函数。
我猜该函数将采用两个参数 cast(x, ref)
,其中 x
是根据 ref
的数据类型转换的变量。
例如:
let myVar = cast(3, "helloworld");
console.log(myVar); // "3"
let myNewVar = cast(myVar, 32423n);
console.log(myNewVar); // 3n
现在,如果 ref
是 bigint
const cast = (n, ref) => typeof ref === "number" ? n : BigInt(n)
最好将一个变量转换为另一个变量的数据类型。
// Cast will attempt to force cast something (n) into the type of
// something else (ref)
const cast = (n, ref) => {
switch(typeof(ref)) // All major types and how to convert them
{
case "boolean": return Boolean(n);
case "number": return Number(n);
case "bigint": return BigInt(n);
case "string": return String(n);
case "symbol": return Symbol(n);
case "undefined": return undefined;
default: return n; // If none of the above is the type, we return n
}
}
// Example: 2 is an int, and the reference is a string, so we cast an int
// to a string, this could be done with various types more complexly
let a = 2
let b = "hello"
a = cast(a, b)
console.log(a, typeof(a)) // 2, string