You still don't understand filter? "JavaScript" "MDN Notes"

content

1. filter "filtering" "what is it?"

Example: Find strings with length greater than 6

grammar:

callback

Attention Points

Demos


1. filter "filtering" "what is it?"

The filter() method creates a new array containing all elements that match the given function.

Example: Find strings with length greater than 6

const words = ['wangjiaran','yezhenkun','yewen','ryker','tom','baby'];
const result = words.filter(word => word.lenth > 6);
console.log(result);
// expected output: Array ["yezhenkun", "wangjiaran"]

grammar:

var newArray = arr.filter(callback(element[,index[,array])[,thisarg])

callback

1. A function to test each element of an array. Returns true if the element passes the test and keeps the element, false if it does not. It accepts the following three parameters:
 2. element "The element currently being processed in the array." index "The index of the element being processed in the array." array "The array itself that called filter."
 3. thisArg "The value used for this when the callback is executed."

Attention Points

1. If a thisArg parameter is provided for filter, it will be used as the this value when the callback is called
Otherwise, the this value of the callback will be the global object in non-strict mode
undefined in strict mode.
2. The range of elements traversed by filter is determined before the callback is called for the first time.
Elements added to the array after calling filter will not be traversed by filter.
If existing elements have been changed, the value they pass into the callback is the value at the moment the filter traversed to them. Elements that are deleted or never assigned a value are not traversed.

Demos

1. Filter to exclude all smaller values

function isBigEnough(x) {
    return x > 10;
}
var arr = [1,2,3,4,5,123,322,9,54,67].filter(isBigEnough);
// console.log(arr);
// filter is[123,322,54,67];

2. Filter invalid entries in JSON

// 过滤JSON中的无效条目
var arr = [
    { id: 15 },
    { id: -1 },
    { id: 0 },
    { id: 3 },
    { id: 12.2 },
    { },
    { id: null },
    { id: NaN },
    { id: 'undefined' }
  ];
// 记录有效长度
  var invalidEntries = 0;
// 
  function isNumber(obj) {
    return obj != undefined && typeof(obj) === 'number' && !isNaN(obj);
  }

  function filterByID(item) {
      if(isNumber(item.id) && item.id !== 0) {
          return true;
      }
      invalidEntries++;
      return false;
  }
  var arrByID = arr.filter(filterByID);

  console.log('Filtered Array\n', arrByID);
// Filtered Array[{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]

  console.log('Number of Invalid Entries = ',invalidEntries);
  // Number of Invalid Entries = 5

Guess you like

Origin blog.csdn.net/weixin_60789461/article/details/123283397