原生js 小知识点

 

 

 

# ==与===区别

    ===需要参数类型相同,==则不需要类型相同

 

#js的循环

(1)of  in区别

   of: 遍历集合本身,in则遍历每一个键值对;即,in的范围要大一些。

var a = ['A', 'B', 'C'];
a.name = 'Hello';

    of包含:A B C;in包含了A B C name

   XXX

(1)forEach

  var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
  m.forEach(function (value, key, map) {
      console.log(""+key+"-"+value);
  });

 

#数组的高阶函数

    (1)map  :每一个元素做操作

      var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      var results = arr.map((x)=>{return x^2;}); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
      console.log(results);

     (2)reduce:每2个元素操作,不断迭代

  效果:[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

      var arr = [1, 3, 5, 7, 9];
      arr.reduce(function (x, y) {
          return x * 10 + y;
      }); // 13579

     (3)filter函数:过滤一些元素

   var arr = [1, 2, 4, 5, 6, 9, 10, 15];
   var r = arr.filter(function (x) {
       return x % 2 !== 0;
   });
   r; // [1, 5, 9, 15]

     (4)sort:排序

   var arr = [10, 20, 1, 2];
   arr.sort(function (x, y) {
       if (x < y) {
           return 1;
       }
       if (x > y) {
           return -1;
       }
       return 0;
   }); // [20, 10, 2, 1]

 

#闭包:闭包经常用于创建含有隐藏数据的函数,闭包就是能够读取其他函数内部变量的函数。

     参看链接https://kb.cnblogs.com/page/110782/。

      http://www.ruanyifeng.com/blog/

 

 

#闭包中的this

https://www.cnblogs.com/nuanriqingfeng/p/5789003.html

 

#call apply

所有函数都有call apply这2个方法。如果不适用他们,那么就需要给函数 显式传入一个上下文对象,略显麻烦。

method.call(obj);//method为方法名,obj为执行此方法的对象。

               function sayHello() {  alert(this.name);  }

               let me = {"name":"leo","age":22};

              sayHello.call(me);

 

call和apply的第一个参数都是对象,call后续的参数是传入的参数序列(不是数组),apply的第二个参数是一个数组。  call(obj,p1,p2,p3);          apply(obj,[p1,p2,p3]);

    function add(c,d){
        return this.a + this.b + c + d;
    }
    var s = {a:1, b:2};
    console.log(add.call(s,3,4)); // 1+2+3+4 = 10
    console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14

#对象属性配置

var myObject = {a:2};

Object.getOwnPropertyDescriptor(myOjbect,"a");  //获取属性的配置

Object.defineProperty(myOjbect,"a",{   //设定属性的配置

    value:2,

    writable:true,

    configurable:true,

    enumerable:true

});

//value :2                值          【好理解】

//writable:true         可写       【好理解】

//enumerable:true  可枚举     【如果设置为false,那么对象(含数组)的for in循环将获取不到该属性,】

//configurable:true   可配置   【 把configurable 修改成false 是单向操作,无法撤销!】

 

PS:通过configurable和writable可以添加一个常量属性。

 

#取消链接的href

  href="javacript:void(0);"

 

 

posted @ 2018-05-05 18:20  东方春  阅读(212)  评论(0编辑  收藏  举报