Js中Array 函数使用方法

遇到数组有关操作,脑子第一反应不要再是嵌套 for 循环了,提供了一些遍历有关的函数。

    : 把数组每个元素丢到一个处理 function 里面,相当于 for 循环。 : 所有数组元素处理后全部 return true,那么就 return true,有点像 &&。 : 只要一个数组元素处理后 return true,那么就 return true,有点像 ||。 : 将处理时 return true 的数组元素拿出来组成一个新数组。 : 对每个数组元素进行处理,并组成一个新数组。 : 像一个累加器一样,把数组元素全部加起来(从左向右)。 : 同上,顺序从右向左。 Array.prototype.square = function () { return this.map(function(n) { return n*n; }); } Array.prototype.average = function () { return this.sum() / this.length; } Array.prototype.sum = function () { return this.reduce(function(a, b) { return a + b; }, 0); } Array.prototype.even = function () { return this.filter(function(item) { return 0 == item % 2; }); } Array.prototype.odd = function () { return this.filter(function(item) { return 0 != item % 2; }); }

例如有道题是要求判断某个值是否存在与一个多层数组(locate([‘a’,’b’,[‘c’,’d’,[‘e’]]],’e’); // should return true)。

var locate = function(arr, v) { var locate = function(arr, v) {
  return arr.some(function(e) { return Array.isArray(e) ? locate(e, v) : e === v; });   return arr.some(function(e) { return Array.isArray(e) ? locate(e, v) : e === v; });
} }
再来一个统计字符串每个字母出现次数的函数: 再来一个统计字符串每个字母出现次数的函数:
function count (string) { function count (string) {
  var count = {};   var count = {};
  string.split().forEach(function(s) {   string.split().forEach(function(s) {
    count[s] ? count[s]++ : count[s] = 1;     count[s] ? count[s]++ : count[s] = 1;
  });   });
  return count;   return count;
} }
function count (string) {   var count = {};   string.split().forEach(function(s) {     count[s] ? count[s]++ : count[s] = 1;   });   return count; }
遇到数组有关操作,脑子第一反应不要再是嵌套 for 循环了,提供了一些遍历有关的函数。 : 把数组每个元素丢到一个处理 function 里面,相当于 for 循环。 : 所有数组元素处理后全部 return true,那么就 return true,有点像 &&。 : 只要一个数组元素处理后 return true,那么就 return true,有点像 ||。 : 将处理时 return true 的数组元素拿出来组成一个新数组。 : 对每个数组元素进行处理,并组成一个新数组。 : 像一个累加器一样,把数组元素全部加起来(从左向右)。 : 同上,顺序从右向左。 Array.prototype.square = function () { return this.map(function(n) { return n*n; }); } Array.prototype.average = function () { return this.sum() / this.length; } Array.prototype.sum = function () { return this.reduce(function(a, b) { return a + b; }, 0); } Array.prototype.even = function () { return this.filter(function(item) { return 0 == item % 2; }); } Array.prototype.odd = function () { return this.filter(function(item) { return 0 != item % 2; }); } 例如有道题是要求判断某个值是否存在与一个多层数组(locate([‘a’,’b’,[‘c’,’d’,[‘e’]]],’e’); // should return true)。 var locate = function(arr, v) {   return arr.some(function(e) { return Array.isArray(e) ? locate(e, v) : e === v; }); } 再来一个统计字符串每个字母出现次数的函数: function count (string) {   var count = {};   string.split().forEach(function(s) {     count[s] ? count[s]++ : count[s] = 1;   });   return count; }
经验分享 程序员 微信小程序 职场和发展