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

基于单参数实现数组及字符串数组中数字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]/gi to find all occurrences of the digit "5"
  • The return logic prioritizes the first array (arr) for counting:
    • If arr has no "5"s but arr1 does → returns 0
    • If arr contains "5"s → returns the count from arr
    • 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)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:32:43