一、Json

javascript object notation js对象简谱。是一种独立于编程语言的轻量级数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,网络传输效率高。
JSON.parse、JSON.stringify。可以将json与json对象进行转换。

二、forEach

forEach遍历函数,对每个元素执行参数函数,没有返回值。
参数一:callback
(1)ele 当前元素
(2)index 可选 当前元素索引
(3)arr 可选 当前遍历的数组
参数二: thisarg 可选,指定callback中的this值(默认指向window。this必须指向一个对象,如果thisarg传原始值,调用call/apply时,会转化为包装类,传null或者undefined无法转换,依然指向window)

es5的方法,兼容es3

  1. Array.prototype.myForEach = function (callback,thisarg){
  2. let originArray = this,
  3. length = this.length,
  4. thisarg = thisarg || window;
  5. for(var i = 0; i < this.length; i++){
  6. callback.apply(arg,[originArray[i], i , originArray])
  7. }
  8. }

中断forEach:
使用break和return都无法中断forEach循环,把forEach放在try catch语法块中,throw一个错误可以终止循环

三、filter过滤

遍历数组, 返回满足测试函数的元素。不会改变原素组。
参数一;
callBack
(1)ele 当前元素
(2)当前元素索引
(3)当前遍历数组
参数二:
thisarg callback中this指向

  1. function deepClone (originObj){
  2. let newObj = {};
  3. for(var i in originObj){
  4. let type = typeof(originObj[i]);
  5. // typeof 返回值有 'number'/ 'string'/'undefined'/'boolean'/'object'/'function'.
  6. //typeof null 和 array为'object'
  7. if( type === 'object' ){
  8. if( (originObj[i] + '') === 'null' ){
  9. newObj[i] = originObj[i]
  10. }else{
  11. newObj[i] = deepClone(originObj[i])
  12. }
  13. }else{
  14. newObj[i] = originObj[i]
  15. }
  16. }
  17. return newObj
  18. }
  19. Array.prototype.myFilter = function(callback,thisarg){
  20. let originArr = this,
  21. length = this.length,
  22. newArr = [];
  23. thisarg = thisarg || window
  24. for(var i = 0; i < originArr.length; i++){
  25. let currentEle = deepClone(originArr[i]) , //新数组不应该继续引用原来数组的元素,所以要进行一次深拷贝
  26. toReturn = callback.apply(thisarg, [currentEle, i, originArr] );
  27. if(toReturn) { newArr.push(currentEle) }
  28. }
  29. return newArr
  30. }

四、map callback函数执行时可以改变原数组。

遍历数组,对每个元素执行callback函数并返回执行结果(默认返回undefined),将执行结果以数组形式返回

  1. Array.prototype.myMap = function(callback, thisarg){
  2. let newArr = [];
  3. thisarg = thisarg || window;
  4. for(var i = 0; i < this.length; i++){
  5. let currentEle = this[i], // 如果不想改变原数组,可以甚克隆当前元素
  6. index = i,
  7. result = callback.apply( thisarg, [currentEle, index, this] );
  8. newArr.push(result)
  9. }
  10. return newArr
  11. }