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

如何用JavaScript实现数组乘法生成重复数字字符串

Solution for Generating Repeated String from Array Pairs

Got it, let's sort out this problem for you! The key issue here is that you're treating the numbers as numeric values (hence getting multiplication results like 1*10=10) instead of converting them to strings to repeat their literal representation.

Here's a straightforward JavaScript function that does exactly what you need:

function repeatNumbers(arr) {
  // Process each subarray into a repeated string
  const resultSegments = arr.map(([number, repeatCount]) => {
    // Convert the number to a string, then repeat it repeatCount times
    return number.toString().repeat(repeatCount);
  });
  
  // Join all segments with ", " to match your expected output format
  return resultSegments.join(', ');
}

// Test the examples you provided
console.log(repeatNumbers([[1, 10]])); // Outputs: "1111111111"
console.log(repeatNumbers([[1, 2], [2, 3]])); // Outputs: "11, 222"

Let's break down how this works:

  • Destructuring in map: We use ([number, repeatCount]) to pull the two values out of each subarray directly, making the code cleaner and easier to read.
  • String conversion: number.toString() turns the numeric value into its string equivalent (so 1 becomes "1"). This is crucial because the repeat() method only exists on strings—numbers don't have this method, which is why your earlier numeric approach didn't work.
  • Repeat the string: repeat(repeatCount) takes the string and duplicates it exactly repeatCount times.
  • Join segments: Finally, join(', ') combines all the repeated strings into one single string separated by , , matching the format you showed in your examples.

Bonus: Handling edge cases

This function also works with multi-digit numbers! For example:

console.log(repeatNumbers([[123, 4]])); // Outputs: "123123123123"

Just make sure the second value in each subarray is a positive integer—if you pass 0 or a negative number, repeat() will return an empty string, which might not be what you want.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:33:29