如何在 Javascript 中将变量转换为另一个变量的类型 [英] How can I cast a variable to the type of another in Javascript

查看:25
本文介绍了如何在 Javascript 中将变量转换为另一个变量的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将一个变量转换为另一个变量的特定类型.举个例子:

I want to be able to cast a variable to the specific type of another. As an example:

function convertToType(typevar, var) {
    return (type typevar)var; // I know this doesn't work
}

这样 convertToType(1, "15") 返回 15,convertToType("1", 15) 返回 "15",convertToType(false, "True") 返回 true,等等

so that convertToType(1, "15") returns 15, convertToType("1", 15) returns "15", convertToType(false, "True") returns true, etc.

重申一下,我希望能够将变量动态转换为其他变量的类型.

To reiterate, I want to be able to dynamically cast variables to the types of other variables.

这可能吗?

推荐答案

function convertToType (t, e) {
    return (t.constructor) (e);
}

注意当我们想将 15 转换为数字时的第一次调用,我们在第一个参数后附加了一个点 (.)

note the first call when we wanted to convert 15 to a Number, we append a dot (.) to the first parameter

这篇关于如何在 Javascript 中将变量转换为另一个变量的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆