You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将OTP输入生成的对象值转换为连续数字?

OTP对象转连续数字的实现方法

这里有几种简单的方案可以将你的OTP对象转换为连续数字:

方案一:直接提取值拼接(适用于键顺序固定的情况)

利用Object.values()获取对象的所有值,通过join('')拼接成字符串后,再转成数字:

const otpObj = {input1: '8', input2: '8', input3: '8', input4: '8'};
// 转为数字类型的8888
const otpNumber = Number(Object.values(otpObj).join(''));
// 如果只需要字符串形式的'8888',去掉Number()即可
const otpString = Object.values(otpObj).join('');

现代浏览器中,Object.values()会按照对象键的插入顺序返回值,对于input1到input4这种命名规范的键,能保证顺序正确。

方案二:指定键顺序提取(更稳妥的方式)

如果需要明确控制值的拼接顺序(比如对象键的顺序不确定时),可以手动定义键的列表来提取对应值:

const otpObj = {input1: '8', input2: '8', input3: '8', input4: '8'};
const otpKeys = ['input1', 'input2', 'input3', 'input4'];
const otpNumber = Number(otpKeys.map(key => otpObj[key]).join(''));

这种方式完全由你控制拼接顺序,避免因对象键顺序变化导致的错误。

内容的提问来源于stack exchange,提问作者Khalid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 14:36:01