JavaScript数组辅助方法练习求助:排查平方、立方函数代码问题
Let's break down what's going wrong with your code and get those square/cube calculations working correctly—plus, since you're practicing array helper methods, I'll show you a cleaner way to do this too!
Issues in Your Current Code
Let's go through the problems one by one:
- Global variable
i: You didn't declareiwithvar,let, orconstin your loops. This makesia global variable, which will cause bugs if you run bothsquare()andcube()(the second function will pick up theivalue where the first left off). - Duplicate elements: In both functions, you're adding each value to the result array twice—once by assigning to
arraySquare[i]and once by callingpush(). That's why yoursquare()function would return[1,1,4,4,...]instead of the expected unique squared values. - Incomplete
cube()function: Yourcube()cuts off mid-return statement—you need to finish it withreturn arrayCube;.
Fixed Version with Traditional Loops
First, let's fix the for-loop approach properly:
var numbers = [1, 2, 3, 4, 5]; function square() { var arraySquare = []; // Declare i locally to avoid global scope issues for (var i = 0; i < numbers.length; i++) { const squared = numbers[i] * numbers[i]; arraySquare.push(squared); // Only push once per element! } return arraySquare; } console.log(square()); // Output: [1, 4, 9, 16, 25] function cube() { var arrayCube = []; for (var i = 0; i < numbers.length; i++) { const cubed = numbers[i] * numbers[i] * numbers[i]; arrayCube.push(cubed); } return arrayCube; // Fixed the incomplete return } console.log(cube()); // Output: [1, 8, 27, 64, 125]
Optimized with Array
map() Helper Method Since you're working on array helper method exercises, map() is the perfect tool here—it creates a new array by applying a function to every element in the original array, which is exactly what we need for squaring/cubing:
const numbers = [1, 2, 3, 4, 5]; // Square using map (arrow function shorthand) const squaredNumbers = numbers.map(num => num * num); console.log(squaredNumbers); // [1, 4, 9, 16, 25] // Cube using map (using exponent operator for brevity) const cubedNumbers = numbers.map(num => num ** 3); console.log(cubedNumbers); // [1, 8, 27, 64, 125]
If you still need to wrap these in functions (like your original code), you can do this:
function square() { return numbers.map(num => num * num); } function cube() { return numbers.map(num => num ** 3); } console.log(square()); // [1, 4, 9, 16, 25] console.log(cube()); // [1, 8, 27, 64, 125]
内容的提问来源于stack exchange,提问作者Feanor Nosselo
相关产品推荐
相关产品推荐

