[英]JavaScript split array in half juxtapose the first half with second half
[英]Finding elements in first half of Javascript array
我對這項練習不太了解。
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)
您應該使用length
屬性檢索數組arr
的length
。 現在,您必須檢查元素index
是否小於length
並在長度為奇數時舍入。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.