关于JavaScript中filter方法参数及代码逻辑的疑问求助
Hey there! As a beginner, it totally makes sense to get stuck on these little details—let's unpack this step by step so everything clicks.
Understanding the filter Method's Callback Parameters
The filter method takes a callback function that runs once for every element in the array. That callback has three optional parameters, which in your code are word, index, and arr:
word: This is the current element being checked in the array. For example, on the first loop,wordis'spray'; on the second loop, it's the already-modified'limit extra', and so on.index: This is the numerical position (starting at 0) of the currentwordin the original array. So'spray'sits at index 0,'limit'at index 1, etc.arr: This is a direct reference to the original array (words) that you calledfilteron. A key thing here: if you modifyarrinside the callback, you're changing the original array itself—this is exactly what's happening in your code!
Breaking Down arr[index+1] += ' extra'
Let's start with what this line does on a basic level: it grabs the element in the array that's one position after the current index, appends ' extra' to it, and saves that modified string back to the original array.
But here's where the confusion (and unexpected behavior) comes in: filter iterates through the array from left to right. Each time you run this line, you're altering the next element before filter even gets to process it. Let's walk through the first few iterations to see the effect:
- First loop (index 0, word = 'spray'): We modify
arr[1](originally'limit') to become'limit extra'. - Second loop (index 1, word = 'limit extra'): Now we're checking the already-changed element. Its length is 11 (way more than 6), so it won't be added to
modifiedWords. Then we modifyarr[2]to'exuberant extra'. - Third loop (index 2, word = 'exuberant extra'): Length is way over 6, so no inclusion. We modify
arr[3]to'destruction extra'. - This pattern continues until the last loop (index 5, word = 'present'): Here,
index+1is 6, which is beyond the original array's length (original indices go 0-5). In JavaScript, accessing an index that doesn't exist returnsundefined, so this line turns intoundefined += ' extra'—resulting in'undefined extra'being added as a new 7th element to the originalwordsarray.
A quick best practice note: Using filter to modify the original array is not ideal. filter is designed to create a new array of elements that meet a condition, not to mutate the original array. If you want to modify elements, map is a better method to use.
Final Results
- The
modifiedWordsarray will only contain['spray']—it's the only element that had a length <6 before any modifications happened. - The original
wordsarray will now look like this:
['spray', 'limit extra', 'exuberant extra', 'destruction extra', 'elite extra', 'present extra', 'undefined extra']
内容的提问来源于stack exchange,提问作者Zowy

