Home  >  Article  >  Web Front-end  >  Share four examples of incorrect use of JavaScript array methods

Share four examples of incorrect use of JavaScript array methods

yulia
yuliaOriginal
2018-09-12 18:02:171460browse

When I first learned JavaScript, I didn’t study it in depth and had only a limited understanding of some knowledge. In the past period of time, these 4 mistakes were made in all the pull requests I checked. Another reason I wrote this article is that I’ve made these mistakes myself. Let’s see how to use them correctly!

1. Don't use Array.indexOf, use Array.includes

"If you want to find an element in an array, use Array.indexOf!". I remember this sentence when I was studying JavaScript courses. This sentence is correct, it can indeed be used in this way!

According to the MDN document: "Array.indexOf will return the subscript of the first matching position of the element being searched for." Therefore, if this index needs to be used later, Array.indexOf is a good solution. However, the problem we want to solve is: find whether an array contains an element. This is a Yes/No question, a true or false question that returns a Boolean type. Therefore, I recommend using Array.includes, which returns a boolean value.

'use strict';
const characters = [
  'ironman',
  'black_widow',
  'hulk',
  'captain_america',
  'hulk',
  'thor',
];
console.log(characters.indexOf('hulk'));
// 2
console.log(characters.indexOf('batman'));
// -1
console.log(characters.includes('hulk'));
// true
console.log(characters.includes('batman'));
// false

2. Don’t use Array.filter, use Array.find

Array.filter is a very useful function that returns a new array that meets the filtering conditions . As its name implies, it is used for filtering.

However, if we know that the result we want has only one element, I do not recommend using it. For example, if our callback function definition uses a unique ID to filter, then the result must be unique. In this case, Array.filter will return an array with only one element. Because since we can search by a specific ID, we have already determined that there is only one element, so using an array makes no sense.

In addition, let’s talk about performance issues. In order to return all matching elements, Array.filter needs to search the entire array. You can imagine that if there are hundreds of elements that meet the filtering conditions, the returned array will be very large.

To avoid this situation, I recommend using Array.find. It only returns the first element that satisfies the filter condition. Moreover, Array.find will end execution after finding the first element that meets the condition, instead of searching the entire array.

'use strict';
const characters = [
  { id: 1, name: 'ironman' },
  { id: 2, name: 'black_widow' },
  { id: 3, name: 'captain_america' },
  { id: 4, name: 'captain_america' },
];
function getCharacter(name) {
  return character => character.name === name;
}
console.log(characters.filter(getCharacter('captain_america')));
// [
//   { id: 3, name: 'captain_america' },
//   { id: 4, name: 'captain_america' },
// ]
console.log(characters.find(getCharacter('captain_america')));
// { id: 3, name: 'captain_america' }

3. Don’t use Array.find, use Array.some

I admit that I have made many mistakes. Later, a very good friend asked me to read the MDN documentation and said that there was a better solution. This situation is very similar to the Array.indexOf/Array.includes just mentioned.

In the previous example, we saw that Array.find accepts a filter function and returns satisfied elements. So, if we want to find whether an array contains a certain element, is Array.find the best solution? Probably not, because it returns the element-specific value, not a boolean value.

I recommend everyone to use Array.some, which will return a Boolean value.

'use strict';
const characters = [
  { id: 1, name: 'ironman', env: 'marvel' },
  { id: 2, name: 'black_widow', env: 'marvel' },
  { id: 3, name: 'wonder_woman', env: 'dc_comics' },
];
function hasCharacterFrom(env) {
  return character => character.env === env;
}
console.log(characters.find(hasCharacterFrom('marvel')));
// { id: 1, name: 'ironman', env: 'marvel' }
console.log(characters.some(hasCharacterFrom('marvel')));
// true

4. Don’t use Array.map and Array.filter combination, use Array.reduce

Array.reduce is a bit difficult to understand! However, if we use Array.filter and Array.map at the same time every time, do you realize that you need something, right?

What I mean is: we looped through the entire array 2 times. The first time is to filter and return a new array, and the second time to construct a new array through map. We use two array methods, each with its own callback function, and the array returned by Array.filter is never used again.

To avoid inefficiency, I recommend using Array.reduce. Same result, more elegant code! Please see the example below:

'use strict';
const characters = [
  { name: 'ironman', env: 'marvel' },
  { name: 'black_widow', env: 'marvel' },
  { name: 'wonder_woman', env: 'dc_comics' },
];
console.log(
  characters
    .filter(character => character.env === 'marvel')
    .map(character => Object.assign({}, character, { alsoSeenIn: ['Avengers'] }))
);
// [
//   { name: 'ironman', env: 'marvel', alsoSeenIn: ['Avengers'] },
//   { name: 'black_widow', env: 'marvel', alsoSeenIn: ['Avengers'] }
// ]
console.log(
  characters
    .reduce((acc, character) => {
      return character.env === 'marvel'
        ? acc.concat(Object.assign({}, character, { alsoSeenIn: ['Avengers'] }))
        : acc;
    }, [])
)
// [
//   { name: 'ironman', env: 'marvel', alsoSeenIn: ['Avengers'] },
//   { name: 'black_widow', env: 'marvel', alsoSeenIn: ['Avengers'] }
// ]

The above is the detailed content of Share four examples of incorrect use of JavaScript array methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn