数组map()方法和filter()方法及字符串startsWith(anotherString)和endsWith(anotherString)方法

map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组

var newArr = arr.map(function() {});
例子:
var data = [1, 2, 3, 4];

var arrayOfSquares = data.map(function (item) {
  return item * item;
});

alert(arrayOfSquares); // 1, 4, 9, 16


Array.prototype扩展可以让IE6-IE8浏览器也支持map方法:

if (typeof Array.prototype.map != "function") {
  Array.prototype.map = function (fn, context) {
    var arr = [];
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {      
         arr.push(fn.call(context, this[k], k, this));
      }
    }
    return arr;
  };
}

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意: filter() 不会对空数组进行检测。

注意: filter() 不会改变原始数组。

array.filter(function(currentValue,index,arr), thisValue)

例子:
var ages = [32, 33, 16, 40];

function checkAdult(age) {
    return age >= 18;
}
function myFunction() {
    document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}

输出结果为:

32,33,40
 
在操作字符串(String)类型的时候,startsWith(anotherString)和endsWith(anotherString)是非常好用的方法
不幸的是,Javascript中没有自带这两个方法,需要的话只能自己写
 
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (prefix){
    return this.slice(0, prefix.length) === prefix;
  };
}

 


原文地址:https://www.cnblogs.com/qhhw/p/5948729.html