第一個函數找到一個數的因子並且工作正常。找到數組的交集找到hcf
//first find divisors of a number
function divisors(n) {
var result = [];
for (var i = 1; i <= n; i++) {
if ((n % i) == 0) {
result.push(i);
}
}
return result;
}
//the following gives problems
function commonTerms(arr1, arr2) {
var arr1 = [];
arr2 = [];
common = [];
var m = Math.min(arr1.length, arr2.length);
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if ((arr1(i)) == (arr2(j))) {
common.push(arr1(i));
} else {
continue;
}
}
}
return common;
}
var x = parseInt(prompt("number to find divisors of?"));
document.write(divisors(x));
var y = parseInt(prompt("number to find divisors of?"));
document.write("<br>" + divisors(y));
alert(commonTerms(divisors(x), divisors(y)));
<!DOCTYPE html>
<html>
<head>
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<h1>GCD</h1>
<p>This is my first website
<br>finding div</p>
</body>
</html>
它不會返回任何東西,第二個功能是一個給我的麻煩。我一直在看它一個小時。開始自己學習編程。 謝謝你的幫助。
你爲什麼要重新定義'VAR ARR1 = []'內部函數'commonTerms' – Rajesh
謝謝,我想這將刪除陣列輸入給 – Kepazino