JS对象与JSON互转换、New Function()、 forEach()、DOM事件流等js开发基础小结


Posted in Javascript onAugust 10, 2017

1、数据类型:JavaScript定义的数据类型有字符串、数字、布尔、数组、对象、Null、Undefined,但typeof有区分可判别的数据分类是number、string、boolean、object(null / array)、function和undefined。undefined 这个值表示变量不含有值,null 可以用来清空变量

let a = 100;
typeof a;//number
a = undefined;
typeof a;//undefined
a = 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;//-2
12 + {a:1};//"12[object Object]"。这里对象先被转换成了字串
null == false;//false
null == 0;//false
null - 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 argument
var 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.

JS对象与JSON互转换、New Function()、 forEach()、DOM事件流等js开发基础小结

(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); // 89
Fibonacci(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) // 573147844013817200000
Fibonacci2(1000) // 7.0330367711422765e+208
Fibonacci2(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

好了以上就是本文对js开发应用中的JS对象与JSON互转换、New Function()、 forEach()遍历、DOM事件流。递归等一些基础知识点的总结啦,希望能够对大家在学习js的过程中有所帮助~

Javascript 相关文章推荐
学习YUI.Ext 第三天
Mar 10 Javascript
jquery 得到当前页面高度和宽度的两个函数
Feb 21 Javascript
jQuery实现指定内容滚动同时左侧或其它地方不滚动的方法
Aug 08 Javascript
jQuery解决input超多的表单提交
Aug 10 Javascript
使用struts2+Ajax+jquery验证用户名是否已被注册
Mar 22 Javascript
详解js前端代码异常监控
Jan 11 Javascript
推荐三款不错的图片压缩上传插件(webuploader、localResizeIMG4、LUploader)
Apr 21 Javascript
详解使用vue实现tab 切换操作
Jul 03 Javascript
利用jQuery+localStorage实现一个简易的计时器示例代码
Dec 25 jQuery
详解关于微信setData回调函数中的坑
Feb 18 Javascript
使用Node.js实现base64和png文件相互转换的方法
Mar 11 Javascript
JavaScript enum枚举类型定义及使用方法
May 15 Javascript
jquery.uploadView 实现图片预览上传功能
Aug 10 #jQuery
express框架实现基于Websocket建立的简易聊天室
Aug 10 #Javascript
bootstrap table服务端实现分页效果
Aug 10 #Javascript
AngularJs+Bootstrap实现漂亮的计算器
Aug 10 #Javascript
React-Native做一个文本输入框组件的实现代码
Aug 10 #Javascript
js实现省市级联效果分享
Aug 10 #Javascript
JavaScript使用Ajax上传文件的示例代码
Aug 10 #Javascript
You might like
php array_flip() 删除数组重复元素
2009/01/14 PHP
php实现图片添加水印功能
2014/02/13 PHP
php通过文件头判断格式的方法
2016/05/28 PHP
PHP高效获取远程图片尺寸和大小的实现方法
2017/10/20 PHP
laravel 修改.htaccess文件 重定向public的解决方法
2019/10/12 PHP
User Scripts: Video Download by User Scripts
2007/05/14 Javascript
js函数般调用正则
2008/04/08 Javascript
js 日期转换成中文格式的函数
2009/07/07 Javascript
jquery中获得$.ajax()事件返回的值并添加事件的方法
2010/04/15 Javascript
Js base64 加密解密介绍
2013/10/11 Javascript
Javascript中对象继承的实现小例
2014/05/12 Javascript
javascript中hasOwnProperty() 方法使用指南
2015/03/09 Javascript
基于Jquery实现焦点图淡出淡入效果
2015/11/30 Javascript
JS未跨域操作iframe里的DOM
2016/06/01 Javascript
详解Vue.js 2.0 如何使用axios
2017/04/21 Javascript
微信小程序之电影影评小程序制作代码
2017/08/03 Javascript
vue-router路由懒加载的实现(解决vue项目首次加载慢)
2018/08/28 Javascript
小程序实现自定义导航栏适配完美版
2019/04/02 Javascript
vue在路由中验证token是否存在的简单实现
2019/11/11 Javascript
[07:09]DOTA2-DPC中国联赛 正赛 Ehome vs Elephant 选手采访
2021/03/11 DOTA
零基础写python爬虫之抓取百度贴吧代码分享
2014/11/06 Python
python实现登陆知乎获得个人收藏并保存为word文件
2015/03/16 Python
怎么使用pipenv管理你的python项目
2018/03/12 Python
Python过滤txt文件内重复内容的方法
2018/10/21 Python
python多进程读图提取特征存npy
2019/05/21 Python
python使用Qt界面以及逻辑实现方法
2019/07/10 Python
python 经典数字滤波实例
2019/12/16 Python
python爬虫爬取监控教务系统的思路详解
2020/01/08 Python
python实现引用其他路径包里面的模块
2020/03/09 Python
Python fileinput模块如何逐行读取多个文件
2020/10/05 Python
python 用Matplotlib作图中有多个Y轴
2020/11/28 Python
Mountain Warehouse波兰官方网站:英国户外品牌
2019/08/29 全球购物
教师创先争优承诺书
2015/04/27 职场文书
2019广播稿怎么写
2019/04/17 职场文书
详解Vue router路由
2021/11/20 Vue.js
Python可视化神器pyecharts绘制水球图
2022/07/07 Python