<!DOCTYPE html>
<html>
<head>
<title>prime</title>
<script>
function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
document.getElementById("results").appendChild(li);
}
function isPrime(value) {
if (value <= 1) {
console.log('抱歉,素数的讨论范围是大于一的自然数')
return alert('抱歉,素数的讨论范围是大于一的自然数')
}
if (!isPrime.cach) {
console.log("创建缓存对象");
isPrime.cach = {};
}
debugger;
if (isPrime.cach[value] !== undefined) {
console.log("缓存里里可以查到");
return isPrime.cach[value]
}
let prime = true;;
for (var i = 2, len = Math.pow(value, 1 / 2); i <= len; i++) {
if (value % i === 0) {
prime = false;
break;
}
}
return isPrime.cach[value] = prime;
}
console.log(isPrime(6))
console.log(isPrime(6))
window.onload = function () {
assert(true, "The test suite is running.");
assert(false, "Fail!");
assert(isPrime(5), "5 is prime!");
assert(isPrime(5), "The answer was cached!");
};
</script>
<style>
#results li.pass {
color: green;
}
#results li.fail {
color: red;
}
</style>
</head>
<body>
<ul id="results"></ul>
</body>
</html>
结果如下: