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

标签 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 half of an array.
// For example, 1 and 2 are in the first half
// arr.
function inFirstHalf(inputArray, element) {

}

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

最佳答案

在将原始数组一分为二创建的新数组中查找值:

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

关于javascript - 在 Javascript 数组的前半部分查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512458/

相关文章:

c++ - 为什么不能像这样 : 在 C++ 中动态声明一个对象数组

javascript - 如何测试一个字符串是否是另一个字符串的最后一个 “part”?

c# - 在字符串中的两个值之间查找单词

JavaScript - 如何从数组数组中删除所有字母

javascript - 错误 "Uncaught SyntaxError: Unexpected token with JSON.parse"

arrays - MATLAB 元胞数组到单个变量

javascript - amcharts javascript 文件的位置

javascript - JavaScript 中的空数组是否为真?

javascript - 如何在表格中插入文本框?

javascript - 如何将 onchange 选定的下拉值存储到隐藏的输入字段中?