JavaScript多维数组质数替换功能实现求助(禁用指定内置函数)
Hey there! Let's walk through fixing this together. You've got the right idea with nested loops to traverse the multidimensional array, but there are a couple of key issues in your current code that we need to address to get the desired output.
Your current condition numbers[i][j] % i === 0 doesn't actually check if a number is prime—you’re using the outer loop’s index i as a divisor, which has no relation to the actual value we’re testing. Let’s build a proper helper function to check for primes, adhering to your restriction of avoiding built-in array methods:
function isPrime(num) { // Handle edge cases first if (num <= 1) return false; if (num === 2) return true; if (num % 2 === 0) return false; // Only check odd divisors up to the square root of the number (efficient!) for (let divisor = 3; divisor * divisor <= num; divisor += 2) { if (num % divisor === 0) { return false; } } return true; }
This function covers all edge cases (numbers ≤1 aren’t prime, 2 is the only even prime) and uses an efficient check by only testing odd divisors up to the square root of the target number.
Your nested loops are the perfect approach (since we can’t use map or other restricted methods), but we need to adjust the logic to:
- Properly test each element with our
isPrimehelper - Replace prime values with
'#'while leaving non-primes untouched - Avoid returning early (your current code returns
falseimmediately, which breaks the loop)
Here’s the revised main function:
function multidimensionalPrimesChecker(numbers) { // Loop through each inner array in the outer array for (var i = 0; i < numbers.length; i++) { // Loop through each element in the current inner array for (var j = 0; j < numbers[i].length; j++) { const currentNum = numbers[i][j]; // Check if the current number is prime if (isPrime(currentNum)) { numbers[i][j] = '#'; } // No action needed for non-primes—they stay as-is } } // Return the modified array return numbers; } // Helper function for prime checking (separated for readability) function isPrime(num) { if (num <= 1) return false; if (num === 2) return true; if (num % 2 === 0) return false; for (let divisor = 3; divisor * divisor <= num; divisor += 2) { if (num % divisor === 0) { return false; } } return true; }
Let’s run this with your sample input to verify it works:
const testInput = [ [5, 7, 10], [8, 2, 3], [44, 50, 22] ]; console.log(multidimensionalPrimesChecker(testInput));
This will output exactly what you expected:[ ['#', '#', 10], [8, '#', '#'], [44, 50, 22] ]
- We avoided all restricted built-in methods (no
map,filter,indexOf, etc.) by relying solely on basicforloops - The
isPrimehelper is efficient and adheres to prime number rules - The main function modifies the input array in place (if you wanted to preserve the original array, you could create a copy with nested loops first, but your example doesn’t require this)
内容的提问来源于stack exchange,提问作者Andy Warhol

