你的位置:首页 > 软件开发 > Java > JavaScript 开发总结(一)

JavaScript 开发总结(一)

发布时间:2017-08-10 13:00:08
数据类型:JavaScript定义的数据类型有字符串、数字、布尔、数组、对象、Null、Undefined,但typeof有区分可判别的数据分类是number、string、boolean、object(null / array)、function和undefined。undef ...

JavaScript 开发总结(一)

  1. 数据类型JavaScript定义的数据类型有字符串、数字、布尔、数组、对象、Null、Undefined,但typeof有区分可判别的数据分类是number、string、boolean、object(null / array)、function和undefined。undefined 这个值表示变量不含有值,null 可以用来清空变量
    let a = 100;typeof a;//numbera = undefined;typeof a;//undefineda = null;typeof a;//null
  2. 默认类型转换:这里列举一部分
    5 == true;//false。true会先转换为1,false转换为0'12' + 1;//'123'。数字先转换成字串'12' - 1;//11。字串先转换成数字[] == false;//true。数组转换为其他类型时,取决于另一个比较者的类型[] == 0;//true[2] == '2';//true[2] == 2;//true[] - 2;//-212 + {a:1};//"12[object Object]"。这里对象先被转换成了字串null == false;//falsenull == 0;//falsenull - 1;//-1
  3. JS对象与JSON互转换:如果要复制对象属性,可通过JSON.stringify()转换成字符串类型,赋值给复制变量后再通过JSON.parse()转换成对象类型,但这种转换会导致原对象方法丢失,只有属性可以保留下来;如果要复制完整对象,需要遍历key:value来复制对象的方法和属性;如果在发生对象赋值后再对其中一个赋新值,其将指向新的地址内容。关于JSON与JavaScript之间的关系:JSON基于 JavaScript 语法,但不是JavaScript 的子集
  4. 大小写切换
    let str = '23abGdH4d4Kd';str = str.replace(/([a-z]*)([A-Z]*)/g, function(match, $1 , $2){return $1.toUpperCase() + $2.toLowerCase()});//"23ABgDh4D4kD"str = 'web-application-development';str = str.replace(/-([a-z])/g, (replace)=>replace[1].toUpperCase());//"webApplicationDevelopment"(驼峰转换)
  5. 生成随机
    str = Math.random().toString(36).substring(2) 
  6. |0、~~取整数:如3.2 / 1.7 | 0 = 1、~~(3.2 / 1.7) = 1。~运算(按位取反)等价于符号取反然后减一,if (!~str.indexOf(substr)) {//do some thing}
  7. 无第三变量交换值:下边的做法未必在空间和时间上都比声明第三变量来的更好,写在这里仅仅为了拓展一下思维
    //方法一:通过中间数组完成交换let a = 1,
    b = 2;a = [b, b = a][0];//方法二:通过加减运算完成交换let a = 1,
    b = 2;a = a + b;b = a - b;a = a - b;//方法三:通过加减运算完成交换let a = 1,
    b = 2;a = a - b;b = a + b;a = b - a;//方法四:通过两次异或还原完成交换。另外,这里不会产生溢出let a = 1,
    b = 2;a = a ^ b;b = a ^ b;a = a ^ b;//方法五:通过乘法运算完成交换let a = 1,
    b = 2;a = b + (b = a) * 0;
  8. /和%运算符

    . 4.53 / 2 = 2.265. 4.53 % 2 = 0.5300000000000002. 5 % 3 = 2
  9. 原型链(Prototype Chaining)与继承: 原型链是ECMAScript 中实现继承的方式。JavaScript 中的继承机制并不是明确规定的,而是通过模仿实现的,所有的继承细节并非完全由解释程序处理,你有权决定最适用的继承方式,比如使用对象冒充(构造函数定义基类属性和方法)、混合方式(用构造函数定义基类属性,用原型定义基类方法)
    function ClassA(sColor) {  this.color = sColor;}ClassA.prototype.sayColor = function () {  alert(this.color);};function ClassB(sColor, sName) {  ClassA.call(this, sColor);  this.name = sName;}ClassB.prototype = new ClassA();ClassB.prototype.sayName = function () {  alert(this.name);};var objA = new ClassA("blue");var objB = new ClassB("red", "John");objA.sayColor();  //输出 "blue"objB.sayColor();  //输出 "red"objB.sayName();  //输出 "John"
  10. call、apply和bind:call和apply的用途都是用来调用当前函数,且用法相似,它们的第一个参数都用作 this 对象,但其他参数call要分开列举,而apply要以一个数组形式传递;bind给当前函数定义预设参数后返回这个新的函数(初始化参数改造后的原函数拷贝),其中预设参数的第一个参数是this指定(当使用new 操作符调用新函数时,该this指定无效),新函数调用时传递的参数将位于预设参数之后与预设参数一起构成其全部参数,bind最简单的用法是让一个函数不论怎么调用都有同样的 this 值。下边的list()也称偏函数(Partial Functions):

    function list() { return Array.prototype.slice.call(arguments);}var list1 = list(1, 2, 3); // [1, 2, 3]// Create a function with a preset leading argumentvar leadingThirtysevenList = list.bind(undefined, 37);var list2 = leadingThirtysevenList(); // [37]var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
  11. Memoization技术: 替代函数中太多的递归调用,是一种可以缓存之前运算结果的技术,这样我们就不需要重新计算那些已经计算过的结果。In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. Although related to caching, memoization refers to a specific case of this optimization, distinguishing it from forms of caching such as buffering or page replacement. In the context of some logic programming languages, memoization is also known as tabling.

    function memoizer(fundamental, cache) {   let cache = cache || {},     shell = function(arg) {       if (! (arg in cache)) {         cache[arg] = fundamental(shell, arg);       }       return cache[arg];     };   return shell;  } 
  12. 闭包(Closure):词法表示包括不被计算的变量(上下文环境中变量,非函数参数)的函数,函数可以使用函数之外定义的变量。下面以单例模式为例来讲述如何创建闭包
    let singleton = function(){ let obj; return function(){    return obj || (obj = new Object()); }}();
  13. New Function():用一个字串来新建一个函数,函数参数可以this.key形式来调用:
    let variables = {  key1: 'value1',  key2: 'value2'},  fnBody = 'return this.key1 + ":" + this.key2',  fn = new Function(fnBody);console.log(fn.apply(variables));
  14. DocumentFragment: Roughly speaking, a DocumentFragment is a lightweight container that can hold DOM nodes. 在维护页面DOM树时,使用文档片段document fragments 通常会起到优化性能的作用

    let ul = document.getElementsByTagName("ul")[0],  docfrag = document.createDocumentFragment();const browserList = [  "Internet Explorer",   "Mozilla Firefox",   "Safari",   "Chrome",   "Opera"];browserList.forEach((e) => {  let li = document.createElement("li");  li.textContent = e;  docfrag.appendChild(li);});ul.appendChild(docfrag);
  15.  forEach()遍历:另外,适当时候也可以考虑使用for 或 for ... in 或 for ... of 语句结构

    1. 数组实例遍历: arr.forEach(function(item, key){    //do some things  })2. 非数组实例遍历: Array.prototype.forEach.call(obj, function(item, key){    //do some things  })3. 非数组实例遍历: Array.from(document.body.childNodes[0].attributes).forEach(function(item, key){    //do some things. Array.from()是ES6新增加的  })
  16. DOM事件流:Graphical representation of an event dispatched in a DOM tree using the DOM event flow.If the bubbles attribute is set to false, the bubble phase will be skipped, and if stopPropagation() has been called prior to the dispatch, all phases will be skipped.

     JavaScript 开发总结(一)

    (1) 事件捕捉(Capturing Phase):event通过target的祖先从window传播到目标的父节点。IE不支持Capturing
    (2) 目标阶段(Target Phase):event到达event的target。如果事件类型指示事件不冒泡,则event在该阶段完成后将停止
    (3) 事件冒泡(Bubbling Phase):event以相反的顺序在目标祖先中传播,从target的父节点开始,到window结束


    事件绑定:

    1. Tag事件属性绑定:<button onclick="do some things"></button>2. 元素Node方法属性绑定:btnNode.onclick = function(){//do some things}3. 注册EventListener:btnNode.addEventListener('click', eventHandler, bubble);另外,IE下实现与W3C有点不同,btnNode.attachEvent(‘onclick’, eventHandler)
  17. 递归与栈溢出(Stack Overflow) :递归非常耗费内存,因为需要同时保存成千上百个调用帧,很容易发生“栈溢出”错误;而尾递归优化后,函数的调用栈会改写,只保留一个调用记录,但这两个变量(func.arguments、func.caller,严格模式“use strict”会禁用这两个变量,所以尾调用模式仅在严格模式下生效)就会失真。在正常模式下或者那些不支持该功能的环境中,采用“循环”替换“递归”,减少调用栈,就不会溢出

    function Fibonacci (n) { if ( n <= 1 ) {return 1}; return Fibonacci(n - 1) + Fibonacci(n - 2);}Fibonacci(10); // 89Fibonacci(50);// 20365011074,耗时10分钟左右才能出结果Fibonacci(100);// 这里就一直出不了结果,也没有错误提示function Fibonacci2 (n , ac1 = 1 , ac2 = 1) { if( n <= 1 ) {return ac2}; return Fibonacci2 (n - 1, ac2, ac1 + ac2);}Fibonacci2(100) // 573147844013817200000Fibonacci2(1000) // 7.0330367711422765e+208Fibonacci2(10000) // Infinity. "Uncaught RangeError:Maximum call stack size exceeded"

    可见,经尾递归优化之后,性能明显提升。如果不能使用尾递归优化,可使用蹦床函数(trampoline)将递归转换为循环:蹦床函数中循环的作用是申请第三者函数来继续执行未完成的任务,而保证自己函数可以顺利退出。另外,这里的第三者和自己可能是同一函数定义

    function trampoline(f) { while (f && f instanceof Function) {  f = f(); } return f;}//改造Fibonacci2()的定义function Fibonacci2 (n , ac1 = 1 , ac2 = 1) { if( n <= 1 ) {return ac2}; return Fibonacci2.bind(undefined, n - 1, ac2, ac1 + ac2);}trampoline(Fibonacci2(100));//573147844013817200000

     

     

原标题:JavaScript 开发总结(一)

关键词:JavaScript

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。