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

如何在JavaScript中根据指定数字重复对应单词?

JavaScript实现数字+单词的重复展开功能

需求是将类似1 jar 2 melon 5 ice的字符串,转换为每个单词重复对应前置数字次数的字符串,最终输出jar melon melon ice ice ice ice ice;另一个示例2 dress 1 mouse 3 jar 1 phone要转换为dress dress mouse jar jar jar phone。

基础实现方案(循环遍历)

这种方式逻辑直观,适合新手理解:

function expandString(input) {
  // 将输入字符串按空格分割成数组
  const parts = input.split(' ');
  const result = [];
  
  // 每次步进2,依次取出数字和对应的单词
  for (let i = 0; i < parts.length; i += 2) {
    const count = parseInt(parts[i], 10);
    const word = parts[i + 1];
    
    // 按数字次数重复添加单词到结果数组
    for (let j = 0; j < count; j++) {
      result.push(word);
    }
  }
  
  // 将结果数组拼接为空格分隔的字符串
  return result.join(' ');
}

// 测试示例
console.log(expandString('1 jar 2 melon 5 ice'));
// 输出: "jar melon melon ice ice ice ice ice"
console.log(expandString('2 dress 1 mouse 3 jar 1 phone'));
// 输出: "dress dress mouse jar jar jar phone"

简洁实现方案(数组方法)

利用数组的Array.from和flat方法,用更精简的代码完成功能:

function expandString(input) {
  const parts = input.split(' ');
  
  // 按每两个元素为一组,生成重复后的子数组,再扁平化并拼接
  return Array.from({ length: parts.length / 2 }, (_, index) => {
    const count = parseInt(parts[index * 2], 10);
    const word = parts[index * 2 + 1];
    return Array(count).fill(word);
  }).flat().join(' ');
}

可选:输入格式校验

如果需要处理不符合格式的输入(比如数字不是正整数、元素个数不成对),可以添加校验逻辑:

function expandString(input) {
  const parts = input.split(' ');
  
  // 检查元素个数是否为偶数(数字+单词成对)
  if (parts.length % 2 !== 0) {
    throw new Error('输入格式错误:必须是数字与单词成对出现');
  }
  
  const result = [];
  for (let i = 0; i < parts.length; i += 2) {
    const count = parseInt(parts[i], 10);
    const word = parts[i + 1];
    
    // 检查数字是否为有效正整数
    if (isNaN(count) || count <= 0) {
      throw new Error(`无效数字:${parts[i]},必须是正整数`);
    }
    
    for (let j = 0; j < count; j++) {
      result.push(word);
    }
  }
  
  return result.join(' ');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:09:34