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

如何将lista数组返回的数值调整为固定8位字符长度的字符串格式

实现方案

你需要对二元组中的频率数值做固定位数的格式化处理,你场景下的音高频率整数部分均为3位,用toFixed(4)保留4位小数后,字符串总长度刚好为8,完全匹配你的需求。

方案1:返回时动态处理

无需修改原有lista的定义,仅在返回结果时做格式化:

const D = [440 * d, 'D']
const DS = [440 * ds, 'D#']
const E = [440 * e, 'E']
const ES = [440 * es, 'E#']
const F = [440 * f, 'F']
const FS = [440 * fs, 'F#']

const lista = [A, AS, B, BS, C, CS, D, DS, E, ES, F, FS]

if(semitons >= 0 && semitons < 13){
  const [freq, noteName] = lista[semitons]
  // toFixed会自动四舍五入,示例数值转换后刚好得到'466.1638'
  return [freq.toFixed(4), noteName]
}

方案2:预先格式化数组内容

直接在定义音高常量时就把频率转为目标格式,后续无需额外处理:

// 前面A、AS、B等常量同步按相同规则处理即可
const D = [(440 * d).toFixed(4), 'D']
const DS = [(440 * ds).toFixed(4), 'D#']
const E = [(440 * e).toFixed(4), 'E']
const ES = [(440 * es).toFixed(4), 'E#']
const F = [(440 * f).toFixed(4), 'F']
const FS = [(440 * fs).toFixed(4), 'F#']

const lista = [A, AS, B, BS, C, CS, D, DS, E, ES, F, FS]

if(semitons >= 0 && semitons < 13){
  return lista[semitons]
}

内容的提问来源于stack exchange,提问作者Gabriel Oliveira Menezes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:09:04