0

this seems like it should be really basic but I'm having issues with it. I'm just starting out so please forgive me if this is answered in other posts - i wasn't able to find anything I know how to apply to my specific issue...I'm wanting to check for numbers 1-4 in an array then build a new array with true or false elements being results of the search...in JS

function linearSearch(vector, x) {
  for (i = 0; i < 4; i++) {
    if (vector[i] == x) {
      return true;
    }
  }
  return false;
}

function checkall() {
  var test = [2, 4, 1, 3];
  var collect = [];
  for (i = 0; i < 4; i++) {
    var ck = linearSearch(test, i + 1);
    collect[i] = ck;
  }
  return collect;
}

console.log(checkall());

2
  • 1
    You need to use var i to make the variable local to each function. Otherwise, when you call linearSearch it changes the value of i in the checkall() loop. Commented Jan 8, 2021 at 16:22
  • Get in the habit of always declaring variables, unless you know you need a global variable. Commented Jan 8, 2021 at 16:23

1 Answer 1

2

You need to declare local variables, preferebly with let for using it in an own scope.

for (let i = 0; i < 4; i++)

If you take it as is, i is declared in global scope and it changes the behavior of the calling loop, as you can see of the below output.

function linearSearch(vector, x) {
  for (i = 0; i < 4; i++) {
    if (vector[i] == x) {
      return true;
    }
  }
  return false;
}

function checkall() {
  var test = [2, 4, 1, 3];
  var collect = [];
  for (i = 0; i < 4; i++) {
    console.log('c0', i);               // should show
    var ck = linearSearch(test, i + 1);
    console.log('c1', i);               // same value
    collect[i] = ck;
  }
  return collect;
}

console.log(checkall());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.