最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JS對象與JSON互轉(zhuǎn)換、New Function()、 forEach()、DOM事件流等js開發(fā)基礎(chǔ)小結(jié)

 更新時間:2017年08月10日 14:41:13   作者:熊貓猛男  
這篇文章主要介紹了JS對象與JSON互轉(zhuǎn)換、New Function()、 forEach()、DOM事件流等js開發(fā)中基礎(chǔ)的知識點,并通過舉例詳細解釋了JavaScript定義的數(shù)據(jù)類型、無第三變量交換值、/和%運算符、Memoization技術(shù)、閉包等知識,需要的朋友可以參考下

1、數(shù)據(jù)類型:JavaScript定義的數(shù)據(jù)類型有字符串、數(shù)字、布爾、數(shù)組、對象、Null、Undefined,但typeof有區(qū)分可判別的數(shù)據(jù)分類是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、默認類型轉(zhuǎn)換:這里列舉一部分

5 == true;//false。true會先轉(zhuǎn)換為1,false轉(zhuǎn)換為0
'12' + 1;//'123'。數(shù)字先轉(zhuǎn)換成字串
'12' - 1;//11。字串先轉(zhuǎn)換成數(shù)字
[] == false;//true。數(shù)組轉(zhuǎn)換為其他類型時,取決于另一個比較者的類型
[] == 0;//true
[2] == '2';//true
[2] == 2;//true
[] - 2;//-2
12 + {a:1};//"12[object Object]"。這里對象先被轉(zhuǎn)換成了字串
null == false;//false
null == 0;//false
null - 1;//-1

3、JS對象與JSON互轉(zhuǎn)換:如果要復(fù)制對象屬性,可通過JSON.stringify()轉(zhuǎn)換成字符串類型,賦值給復(fù)制變量后再通過JSON.parse()轉(zhuǎn)換成對象類型,但這種轉(zhuǎn)換會導(dǎo)致原對象方法丟失,只有屬性可以保留下來;如果要復(fù)制完整對象,需要遍歷key:value來復(fù)制對象的方法和屬性;如果在發(fā)生對象賦值后再對其中一個賦新值,其將指向新的地址內(nèi)容。關(guān)于JSON與JavaScript之間的關(guān)系: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"(駝峰轉(zhuǎn)換)

5、生成隨機數(shù):

str = Math.random().toString(36).substring(2) 

6、|0、~~取整數(shù):如3.2 / 1.7 | 0 = 1、~~(3.2 / 1.7) = 1。~運算(按位取反)等價于符號取反然后減一,if (!~str.indexOf(substr)) {//do some thing}

7、無第三變量交換值:下邊的做法未必在空間和時間上都比聲明第三變量來的更好,寫在這里僅僅為了拓展一下思維

//方法一:通過中間數(shù)組完成交換
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;
//方法四:通過兩次異或還原完成交換。另外,這里不會產(chǎn)生溢出
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 中實現(xiàn)繼承的方式。JavaScript 中的繼承機制并不是明確規(guī)定的,而是通過模仿實現(xiàn)的,所有的繼承細節(jié)并非完全由解釋程序處理,你有權(quán)決定最適用的繼承方式,比如使用對象冒充(構(gòu)造函數(shù)定義基類屬性和方法)、混合方式(用構(gòu)造函數(shù)定義基類屬性,用原型定義基類方法)

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的用途都是用來調(diào)用當(dāng)前函數(shù),且用法相似,它們的第一個參數(shù)都用作 this 對象,但其他參數(shù)call要分開列舉,而apply要以一個數(shù)組形式傳遞;bind給當(dāng)前函數(shù)定義預(yù)設(shè)參數(shù)后返回這個新的函數(shù)(初始化參數(shù)改造后的原函數(shù)拷貝),其中預(yù)設(shè)參數(shù)的第一個參數(shù)是this指定(當(dāng)使用new 操作符調(diào)用新函數(shù)時,該this指定無效),新函數(shù)調(diào)用時傳遞的參數(shù)將位于預(yù)設(shè)參數(shù)之后與預(yù)設(shè)參數(shù)一起構(gòu)成其全部參數(shù),bind最簡單的用法是讓一個函數(shù)不論怎么調(diào)用都有同樣的 this 值。下邊的list()也稱偏函數(shù)(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技術(shù): 替代函數(shù)中太多的遞歸調(diào)用,是一種可以緩存之前運算結(jié)果的技術(shù),這樣我們就不需要重新計算那些已經(jīng)計算過的結(jié)果。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):詞法表示包括不被計算的變量(上下文環(huán)境中變量,非函數(shù)參數(shù))的函數(shù),函數(shù)可以使用函數(shù)之外定義的變量。下面以單例模式為例來講述如何創(chuàng)建閉包

let singleton = function(){
 let obj;
 return function(){
 return obj || (obj = new Object());
 }
}();

13、New Function():用一個字串來新建一個函數(shù),函數(shù)參數(shù)可以this.key形式來調(diào)用:

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 通常會起到優(yōu)化性能的作用

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()遍歷:另外,適當(dāng)時候也可以考慮使用for 或 for ... in 或 for ... of 語句結(jié)構(gòu)

1. 數(shù)組實例遍歷: arr.forEach(function(item, key){
        //do some things
    })
2. 非數(shù)組實例遍歷: Array.prototype.forEach.call(obj, function(item, key){
        //do some things
    })
3. 非數(shù)組實例遍歷: 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.

(1) 事件捕捉(Capturing Phase):event通過target的祖先從window傳播到目標(biāo)的父節(jié)點。IE不支持Capturing
(2) 目標(biāo)階段(Target Phase):event到達event的target。如果事件類型指示事件不冒泡,則event在該階段完成后將停止
(3) 事件冒泡(Bubbling Phase):event以相反的順序在目標(biāo)祖先中傳播,從target的父節(jié)點開始,到window結(jié)束

事件綁定:

1. Tag事件屬性綁定:<button onclick="do some things"></button>
2. 元素Node方法屬性綁定:btnNode.onclick = function(){//do some things}
3. 注冊EventListener:btnNode.addEventListener('click', eventHandler, bubble);另外,IE下實現(xiàn)與W3C有點不同,btnNode.attachEvent(‘onclick', eventHandler)

17、遞歸與棧溢出(Stack Overflow) :遞歸非常耗費內(nèi)存,因為需要同時保存成千上百個調(diào)用幀,很容易發(fā)生“棧溢出”錯誤;而尾遞歸優(yōu)化后,函數(shù)的調(diào)用棧會改寫,只保留一個調(diào)用記錄,但這兩個變量(func.arguments、func.caller,嚴格模式“use strict”會禁用這兩個變量,所以尾調(diào)用模式僅在嚴格模式下生效)就會失真。在正常模式下或者那些不支持該功能的環(huán)境中,采用“循環(huán)”替換“遞歸”,減少調(diào)用棧,就不會溢出

function Fibonacci (n) {
 if ( n <= 1 ) {return 1};
 return Fibonacci(n - 1) + Fibonacci(n - 2);
}
Fibonacci(10); // 89
Fibonacci(50);// 20365011074,耗時10分鐘左右才能出結(jié)果
Fibonacci(100);// 這里就一直出不了結(jié)果,也沒有錯誤提示

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"

可見,經(jīng)尾遞歸優(yōu)化之后,性能明顯提升。如果不能使用尾遞歸優(yōu)化,可使用蹦床函數(shù)(trampoline)將遞歸轉(zhuǎn)換為循環(huán):蹦床函數(shù)中循環(huán)的作用是申請第三者函數(shù)來繼續(xù)執(zhí)行未完成的任務(wù),而保證自己函數(shù)可以順利退出。另外,這里的第三者和自己可能是同一函數(shù)定義

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開發(fā)應(yīng)用中的JS對象與JSON互轉(zhuǎn)換、New Function()、 forEach()遍歷、DOM事件流。遞歸等一些基礎(chǔ)知識點的總結(jié)啦,希望能夠?qū)Υ蠹以趯W(xué)習(xí)js的過程中有所幫助~

相關(guān)文章

最新評論

郸城县| 湖南省| 芦溪县| 云龙县| 辰溪县| 堆龙德庆县| 同心县| 鲁甸县| 鹿邑县| 绥中县| 安西县| 会宁县| 宁南县| 华安县| 台南市| 汝阳县| 佳木斯市| 濮阳市| 松阳县| 中超| 平江县| 依兰县| 巫溪县| 右玉县| 获嘉县| 赤城县| 石首市| 固原市| 沁阳市| 曲阳县| 南昌市| 盐源县| 库尔勒市| 汝州市| 绥德县| 灵石县| 武冈市| 西和县| 广灵县| 太湖县| 襄樊市|