基于单参数实现数组及字符串数组中数字5的重复次数统计
Solution: Convert the Two-Parameter Function to a Single-Parameter Version
First, Let's Break Down the Original Logic
Before modifying the function, let's clarify what count5numbers1 actually does:
- It converts both input arrays to strings, then uses the regex
/[5]/gito find all occurrences of the digit "5" - The return logic prioritizes the first array (
arr) for counting:- If
arrhas no "5"s butarr1does → returns 0 - If
arrcontains "5"s → returns the count fromarr - If both arrays have no "5"s → returns the string
"it's not a number" - As a fallback, returns the count from
arr1(this case doesn't show up in your test examples, but we'll keep it intact)
- If
Revised Single-Parameter Function
To switch to a single parameter, we can pass the two original arrays as elements of a single input array. Here's the updated code:
function count5numbers(inputArrays) { // Destructure the single input array into the original two arrays const [arr, arr1] = inputArrays; let m1 = arr.toString().match(/[5]/gi); let m2 = arr1.toString().match(/[5]/gi); if (m1 === null && m2 != null) { return 0; } else if (m1 != null) { return m1.length; } else if (m2 === null) { return "it's not a number"; } else { return m2.length; } }
Test the Modified Function
Just wrap your original arguments in an array when calling the new function, and you'll get the exact same output as before:
console.log(count5numbers([[1, 2, 5, 43], [5]])); // 1 console.log(count5numbers([[1, 2, 3, 5], [5]])); // 1 console.log(count5numbers([[1, 2, 4, 2], [5]])); // 0 console.log(count5numbers([[2, 4, 54, 15], [5]])); // 2 console.log(count5numbers([[1, 5, 55, 555], [5]])); // 6 console.log(count5numbers([[6, 3, 2, 1], [5]])); // 0 console.log(count5numbers([['notnumber,its a string'], []])); // it's not a number
Alternative: Use an Object for Readability
If you prefer more explicit argument names, you can also accept an object as the single parameter:
function count5numbers({ arr, arr1 }) { let m1 = arr.toString().match(/[5]/gi); let m2 = arr1.toString().match(/[5]/gi); if (m1 === null && m2 != null) { return 0; } else if (m1 != null) { return m1.length; } else if (m2 === null) { return "it's not a number"; } else { return m2.length; } }
Call it like this for clearer code:
console.log(count5numbers({ arr: [1, 2, 5, 43], arr1: [5] })); // 1
Both approaches preserve the original function's behavior while using only one parameter.
内容的提问来源于stack exchange,提问作者Lawrence
相关产品推荐
相关产品推荐

