.splice()
changes the array it is used on. You might have already known this, but if you debug your code using a console.log
, you'll see what's happening; in short, your first number > 5 is 15. 15 is at index 0, so you remove index 0. However, as splice changes the array it is used on, 12 becomes index 0, and then the second 15 index 1, and so on and so forth. So for example, your code has the following indexes: 0, 1, 2, 6.
- The first time you remove index 0:
[12, 15, 3, 5, 4, 6]
- Then you remove index 1:
[12, 3, 5, 4, 6]
- Then you remove index 2:
[12, 3, 4, 6]
- Then you remove index 6, which doesn't exist:
[12, 3, 4, 6]
The better way of accomplishing that goal is with .filter()
. Filter creates a new array of all items that pass the test given in the callback, so:
numbers = numbers.filter((num) => num < 6);
That's the arrow function expression shorthand to return only numbers less than 6.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…