简体   繁体   中英

How to code a function that checks if an array contains a number by returning a boolean

I just started learning code and i'm currently stuck on the following assignment.

Assignment:

Code a function that checks if an array contains a number by returning a boolean.(Java code)

Examples: contains([1, 2, 3, 4], 3) returns true. contains([2, 2, 4], 3) returns false.

I've tried the following:

code

Can anyone help me with solving this one?

You can use the includes() method which is available for JavaScript arrays. It will check if a specific element is included in the array and will return a boolean value of either true or false.

function contains(array, number){
    var ans = array.includes(number);
    return ans;
}

console.log(contains([1,2,3,4],3)); // Prints true
console.log(contains([2,2,4],3));   // Prints false

An array is a collection of elements of a specific type. Your function takes two parameters: the array in which you want to search, and the number you want to search.

To achieve this, you have to iterate through the array, using a controlled iteration like a for loop . The loop takes all elements in the array one by one, and performs an action that you define in the loop body, in your case you can compare the current array element to the one passed to your function. If they are the same, you can return from the loop using the return statement. If all elements were

Assuming that you're using JavaScript, you'd do something like this using the for statement :

function contains(array, number){
    for(var currentElementIndex in array) {
        if(array[currentElementIndex] === number) {
            return true;
        }
    }
    return false;
}

You should iterate for each array element. Considering that your array contains numbers check the following function

function contains(numberArray, check){
  var i;
  for (i = 0; i < numberArray.length; i++) {
    if (numberArray[i] == check){
      return true;
    }
  }
    return false;
}

It takes the numberArray array as input and the check number. Then it iterates for each number in the array and checks if it finds the same number with the check number.

If it finds it, then it returns true and the loop breaks.

If it does not find it, after the loop is finished iterating all the elements of the array, then it returns false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM