用于循环math.sqrt()的JavaScript

时间:2015-10-12 02:51:13

标签: javascript for-loop

我正在尝试编写一个显示数字1到25平方的for循环。

我完全陷入困境。

function square(){
var squareRoot = Math.sqrt(2);
var square = squareRoot;

for (square = 0; square < 25; counter++){


}

console.log(squareRoot);

2 个答案:

答案 0 :(得分:0)

平方:

http://jsfiddle.net/ryanpcmcquen/n24vyexx/

for (var i = 1; i < 26; i++) {
  console.log(i * i);
}

OR:

http://jsfiddle.net/ryanpcmcquen/0g0rqe4p/

for (var i = 1; i < 26; i++) {
  console.log(Math.pow(i, 2));
}

平方根:

http://jsfiddle.net/ryanpcmcquen/4uep39ev/

for (var i = 1; i < 26; i++) {
  console.log(Math.sqrt(i));
}

答案 1 :(得分:0)

虽然有一个更简单,更直接的解决方案,但您可能希望以后能够快速查找计算结果。

在这种情况下,您可以将结果存储在对象中。

// first initialize an object for the results to be stored for later use
var results = {};

// define our computation
function squared(x) {
    return x * x;
}

// loop from 1 to 25 inclusive
for (var i = 1; i <= 25; ++i) {
    results[i] = squared(i); // compute and store the result
    console.log(i, 'squared is:', results[i]); // print out the result
}

这种方法可让您在以后快速查找结果,而无需再次进行计算。

// you can get existing values
console.log(results[7]); // should print out the result 49

// you can also compute and add the results to your results object
results[100] = squared(100); // stores the result 10000 as value for the key 100