如何用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 (so1becomes"1"). This is crucial because therepeat()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 exactlyrepeatCounttimes. - 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
相关产品推荐
相关产品推荐

