我需要做什么:
// Return an array containing the second half of an array
// Exclude middle index on odd length arr
我的代碼:
function secondHalf(arr) {
let newArr = [];
for (let i = Math.floor(arr.length / 2); i >= 0; i--) {
newArr.push(arr[i]);
} return newArr;
}
secondHalf([1, 2]);
secondHalf([1]);
我得到的輸出:
1) Problems
secondHalf
should return only the second half the array:
AssertionError: expected [ 2, 1 ] to deeply equal [ 2 ]
expected - actual
[
2
- 1
]
at Context.<anonymous> (test/problems-specs.js:72:48)
at processImmediate (node:internal/timers:466:21)
2) Problems
secondHalf
should be the exclusive first half:
AssertionError: expected [ 1 ] to deeply equal []
expected - actual
-[
- 1
-]
[]
at Context.<anonymous> (test/problems-specs.js:75:45)
at processImmediate (node:internal/timers:466:21)
我已經嘗試了很多次,遇到了類似但沒有使用它們的方法.splice(),因為我只需要使用回圈來解決它。.slice()我究竟做錯了什么?
uj5u.com熱心網友回復:
您可以使用i設定為四舍五入長度的一半的“正常”for回圈:
function secondHalf(arr) {
let newArr = [];
for (let i = Math.ceil(arr.length / 2); i < arr.length; i ) {
newArr.push(arr[i]);
}
return newArr;
}
console.log(secondHalf([1, 2, 3, 4, 5, 6, 7]));
console.log(secondHalf([1, 2, 3, 4]));
console.log(secondHalf([1, 2, 3]));
console.log(secondHalf([1, 2]));
console.log(secondHalf([1]));
編輯:發生的事情是 for 回圈條件部分分為三個部分:
let i = Math.ceil(arr.length / 2);i < arr.length;i
這是完成所有“魔術”的第一部分。我們不是從陣列長度的一半開始迭代,而是從0四舍五入開始,這意味著如果我們有一個像這樣的陣列:
[1, 2, 3, 4, 5, 6, 7]
| | | | | | |
0 1 2 3 4 5 6
|
we start from here
長度的一半是 3.5 (7 / 2),四舍五入:4
這意味著我們從索引 4 開始迭代:
// this is what is happening at each iteration of the for loop:
// i = 4
newArr.push(arr[4]); // which is the number 5
// i = 5
newArr.push(arr[5]); // which is the number 6
// i = 6
newArr.push(arr[6]); // which is the number 7
// i is not below arr.length anymore, so stop iterating
這有點幫助嗎?
uj5u.com熱心網友回復:
function secondHalf(arr) {
let newArr = []
for (let i = 1; i <= Math.floor(arr.length / 2); i ) {
newArr.push(arr[arr.length-i])
}
return newArr
}
secondHalf([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
uj5u.com熱心網友回復:
試試這個兄弟,這里我首先檢查陣列的長度,如果長度不能被 2 整除,則通過加 1 洗掉中間項,如果長度是偶數,則通過除以陣列長度來考慮第二部分。
function secondHalf(array) {
var secArr = [];
let index = 0;
if(array.length % 2 !== 0) {
index = parseInt(array.length / 2) 1;
} else index = array.length /2;
for(let i= index; i<array.length; i ) {
secArr.push(array[i]);
}
return secArr;
}
秒半([1,2,3,4,5])
uj5u.com熱心網友回復:
更清潔的方法:
function secondHalf(arr) {
const len = arr.length;
return arr.slice(Math.ceil(len / 2), len);
}
console.log(secondHalf([1, 2, 3, 4, 5, 6]));
console.log(secondHalf([1, 2, 3, 4, 5]));
console.log(secondHalf([1, 2, 3, 4]));
console.log(secondHalf([1]));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/522884.html
