[英]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)编写一个 function 代码,通过返回 boolean 来检查数组是否包含数字。(Java 代码)
Examples: contains([1, 2, 3, 4], 3) returns true.示例: contains([1, 2, 3, 4], 3) 返回 true。 contains([2, 2, 4], 3) returns false.
contains([2, 2, 4], 3) 返回 false。
I've tried the following:我尝试了以下方法:
Can anyone help me with solving this one?谁能帮我解决这个问题?
You can use the includes() method which is available for JavaScript arrays.您可以使用可用于 JavaScript arrays 的 includes() 方法。 It will check if a specific element is included in the array and will return a boolean value of either true or false.
它将检查特定元素是否包含在数组中,并将返回 boolean 值 true 或 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.
您的 function 有两个参数:要搜索的数组和要搜索的数字。
To achieve this, you have to iterate through the array, using a controlled iteration like a for loop .为此,您必须使用诸如for 循环之类的受控迭代来遍历数组。 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.
循环将数组中的所有元素一一获取,并执行您在循环主体中定义的操作,在您的情况下,您可以将当前数组元素与传递给 function 的元素进行比较。 If they are the same, you can return from the loop using the
return
statement.如果它们相同,则可以使用
return
语句从循环中返回。 If all elements were如果所有元素都是
Assuming that you're using JavaScript, you'd do something like this using the for statement :假设您使用的是 JavaScript,您可以使用for 语句执行以下操作:
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
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.它将 numberArray 数组作为输入和校验号。 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.如果找到它,则返回 true 并且循环中断。
If it does not find it, after the loop is finished iterating all the elements of the array, then it returns false.如果没有找到,则在循环完成对数组的所有元素的迭代后,它会返回 false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.