user5723270 - 4 years ago 139

Javascript Question

The first function find factors of a number and works fine.

`//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>

It won't return anything, the second function is the one giving me trouble. I have been looking at it for an hour. Starting to learn programming on my own.

Thank you for your help.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The problem is that you're accessing array items like this: `arr(i)`

.
You should do it with square brackets:

```
if ((arr1[i])==(arr2[j])){
common.push(arr1[i]);
//...
}
```

And you don't need the round braces at all. Plus you'd better use strict comparison (`===`

instead of `==`

).

So it would be:

```
if (arr1[i] === arr2[j]){
common.push(arr1[i]);
//...
}
```

BTW Consider checking this question

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**