Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript数组的前半部分中查找元素_Javascript_Arrays_Indexof - Fatal编程技术网

在Javascript数组的前半部分中查找元素

在Javascript数组的前半部分中查找元素,javascript,arrays,indexof,Javascript,Arrays,Indexof,我不太懂这个练习 arr = [1, 2, 3]; arr.indexOf(2); // 1 arr.indexOf(4); // -1 since it doesn't exist. // Write a function to determine if an element // is in the first half of an array. // If an element has an odd length, round up // when counting the first

我不太懂这个练习

arr = [1, 2, 3];
arr.indexOf(2); // 1
arr.indexOf(4); // -1 since it doesn't exist.

// Write a function to determine if an element
// is in the first half of an array.
// If an element has an odd length, round up
// when counting the first half of an array.
// For example, 1 and 2 are in the first half
// arr.
function inFirstHalf(inputArray, element) {

}

我不明白,数组的前半部分是什么意思?

您应该使用
length
属性检索数组的长度
arr
。现在,您必须检查元素
索引
是否小于
长度
,并在长度为奇数时进行取整

function inFirstHalf(inputArray, element) {
    if ((inputArray.length % 2) === 0) {
        if ((inputArray.indexOf(element) + 1) <= (inputArray.length / 2)) {
            return true;
        }
    } else {
        if ((inputArray.indexOf(element) + 1) <= Math.ceil ((inputArray.length / 2))) {
            return true;
        }
    }
    return false;
}
函数infrasthalf(输入阵列,元素){
如果((inputArray.length%2)==0){

如果((inputArray.indexOf(element)+1)在通过将原始数组分为两部分创建的新数组中查找值:

arr.slice(0, Math.ceil(arr.length/2)) . indexOf(val)

我猜这意味着如果indexOf返回的值小于arr.length的一半,如果length为奇数,则向上取整(这意味着您实际上必须向下取整,因为数组索引从0开始)@RobG你让我开心!谢谢@RobG,我正在学习这门课程,我被困在了那个练习中。你能举一些例子说明你是如何测试这个的吗?如果索引小于
inputArray.length/2
,那么根据定义,它也将小于该值的上限,所以第二次检查似乎是不必要的,除非我遗漏了在这种方法中,由于第一个if语句,第二次检查是必要的。第一步是检查数组长度是否为奇数。当长度不是奇数时,
inputArray.length/2
检查适用。否则(当数组长度为奇数时)
Math.ceil
检查适用。即使这种方法不是最好的(也不是很好的)方法,任务也将通过建议的codeacadamy技术解决(这就是本练习的目的)。