Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

JavaScript - Unexpected result while remove elements from an array using Array.prototype.splice

i know this is an annoying question, but can someone explain me why splice method is executing in a weird way. Please explain me why the expected output is different from the actual result.


let numbers = [15, 12, 15, 3, 5, 4, 6];

// Get the indexes of the numbers greater than 5
let indexes = numbers.reduce((arr, current, index) => {
  if (current > 5) {
    arr.push(index);
  }

  return arr;
}, []);

// Loop through the indexes while removing the indexes from the numbers array
indexes.forEach((element) => {
  numbers.splice(element, 1);
});

// expected result: numbers = [ 3 , 5, 4 ];
// actual result: numbers = [ 12, 3, 4, 6 ]

question from:https://stackoverflow.com/questions/65932997/javascript-unexpected-result-while-remove-elements-from-an-array-using-array-p

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...