Array方法学习小结

原生js forEach()和map()遍历

A:相同点:

   1.都是循环遍历数组中的每一项。

   2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。

   3.匿名函数中的this都是指Window。

   4.只能遍历数组。

B:不同

1.forEach()

   没有返回值

  var ary = [12,23,2,3]; 

  var res = ary.forEach(function (item,index,ary) {  

     input[index] = item*10;  

  })  

  console.log(res);//-->undefined;  

  console.log(ary);//-->会对原来的数组产生改变;

2.map()

  有返回值,可以return 出来。

  var ary = [12,2,4,22,1];  

  var res = ary.map(function (item,index,ary) {  

    return item*10;  

  })  

  console.log(res);//[120,20,40,220,10];  

  console.log(ary);//[12,2,4,22,1];  

3.filter()筛选(从这个https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter网站上copy的demo)

筛选值

function isBigNum(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 10, 40].filter(isBigNum);
// filtered is [12, 10, 40]

筛选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

数组中筛选:

var color = ['red', 'grey', 'green', 'yellow', 'orange'];

/**
 * Array filters items based on search criteria (query)
 */
function filterItems(query) {
  return color.filter(function(el) {
      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
  })
}

console.log(filterItems('re')); // ['red', 'grey', 'green']
console.log(filterItems('or')); // ['orange']

ES5实现

var color = ['red', 'grey', 'green', 'yellow', 'orange'];
const filterItems = (query) => {
  return color.filter((el) =>
    el.toLowerCase().indexOf(query.toLowerCase()) > -1
  );
}
console.log(filterItems('re')); // ['red', 'grey', 'green']
console.log(filterItems('or')); // ['orange']

目前先整理这么多,等下次有时间接着整理。 

posted @ 2018-12-10 18:25  青青子衿619  阅读(176)  评论(0编辑  收藏  举报