在数字数组上循环不会对数字求平方

时间:2019-11-09 04:21:30

标签: javascript math

我正在尝试让我的类代码产生所需的结果,但是我在这里得到的内容并没有达到我的期望。

这是我正在测试的代码:

const sampleArray = [
  876, 755, 661, 24532, 758, 450,
  302, 2043, 712, 71, 456, 21, 398,
  339, 882, 9, 179, 535, 940, 12
];

let myFunction = function() {
  let squareNumbers = [];

  for (let counter4 = 0; counter4 < sampleArray.length; counter4++) {
    if (Math.pow(sampleArray[counter4], 2)) {
      squareNumbers.push(sampleArray[counter4])
    }
  }

  console.log(squareNumbers);
}

myFunction();

它显示了数组中的项,但没有将它们平方,我不知道为什么。我已经以不同的方式找到了解决方案,但是我觉得应该可以做些更好的事情

1 个答案:

答案 0 :(得分:1)

好的,我明白你的要求了。怎么样:

calling manager.Testclass(arr)
TestClass.__init__ called, a = array([0, 0, 0, 0])
result: managed_obj = <TestProxy object, typeid 'Testclass' at 0x4b3f520>

executing managed_obj.my_setitem(name='a', index=1, 42)
in TestProxy.my_setitem()
in TestClass.my_setitem()
result: managed_obj.a = array([ 0, 42,  0,  0])

产生以下结果:

// unchanged
const sampleArray = [876, 755, 661, 24532, 758, 450, 302, 2043, 712, 71, 456, 21, 398, 339, 882, 9, 179, 535, 940, 12];

// unchanged
let squareNumbers = [];

// unchanged
let myFunction = function() {

  // unchanged
  for (let counter4 = 0; counter4 < sampleArray.length; counter4++) {

    // minor change...
    // Math.pow(sampleArray[counter4], 2) squares the number
    // but it only returns the number. 
    // If used within an "if" is returns a form of "true". 
    var mysquare = Math.pow(sampleArray[counter4], 2);

    // this is not required..it's just so you can see "the return"
    console.log("the squre of " + sampleArray[counter4] + " is " + mysquare);

    // To "put it in the array" you must push "the return" onto the array. 
    squareNumbers.push(mysquare)
  }
}

// unchanged
myFunction();
console.log('my squareNumbers:');
console.log(squareNumbers);