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

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 declare i with var, let, or const in your loops. This makes i a global variable, which will cause bugs if you run both square() and cube() (the second function will pick up the i value 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 calling push(). That's why your square() function would return [1,1,4,4,...] instead of the expected unique squared values.
  • Incomplete cube() function: Your cube() cuts off mid-return statement—you need to finish it with return 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:17:41