цикл по массиву чисел не возводит числа в квадрат - PullRequest
2 голосов
/ 09 ноября 2019

Я пытаюсь получить свой код для класса, чтобы получить желаемые результаты, но то, что у меня есть, не делает то, что я хотел.

Это код, который яtesting:

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 Ответ

1 голос
/ 09 ноября 2019

Хорошо, я вижу, что вы после. Как насчет этого:

// 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);

, который производит это:

the squre of 876 is 767376
the squre of 876 is 767376
the squre of 755 is 570025
the squre of 661 is 436921 
the squre of 24532 is 601819024 
the squre of 758 is 574564 
the squre of 450 is 202500 
the squre of 302 is 91204
the squre of 2043 is 4173849 
the squre of 712 is 506944
the squre of 71 is 5041 
the squre of 456 is 207936 
the squre of 21 is 441 
the squre of 398 is 158404
the squre of 339 is 114921 
the squre of 882 is 777924 
the squre of 9 is 81 
the squre of 179 is 
the squre of 535 is 
the squre of 940 is 
the squre of 12 is 144
my squareNumbers:
Array(20) [ 767376, 570025, 436921, 601819024, 574564, 202500, 91204, 4173849, 506944, 5041, … ]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...