1 JavaScript面试真题-210页
1 JavaScript面试真题-210页
JavaScript
1
1 let intNum = 55 // 10 55
2 let num1 = 070 // 8 56
3 let hexNum1 = 0xA //16 10
NaN
1 console.log(0/0); // NaN
2 console.log(-0/+0); // NaN
1 let message;
2 console.log(message == undefined); // true
undefined
2
1 let message; // undefined
2
3 console.log(message); // "undefined"
4 console.log(age); //
Null null
undefined null
null
3
Boolean
1 true false
2 String ""
3 Number 0 NaN
4 Object null
5 Undefined N/A undefined
Object
object
4
1 let person = {
2 name: "Nicholas",
3 "age": 29,
4 5: true
5 };
JavaScript
Function Function
1 //
2 function sum (num1, num2) {
3 return num1 + num2;
4 }
5
1 let sum = (num1, num2) => {
2 return num1 + num2;
3 };
1 let a = 10;
2 let b = a; //
3 b = 20;
4 console.log(a); // 10
a a b
6
1 var obj1 = {}
2 var obj2 = obj1;
3 obj2.name = "Xxx";
4 console.log(obj1.name); // xxx
obj1
obj2 obj2 obj1
7
8
9
10
11
12
HTML XML
1 <html>
2 <head>
3 <title>Page</title>
4 </head>
5 <body>
6 <p>Hello World!</p >
7 </body>
8 </html>
DOM DOM
1 <div>
2 <p title="title">
3 content
4 </p >
5 </div>
DOM
DOM
DOM
13
DOM
DocumentFragment DocumentFragment
14
1 const dataAttribute = document.createAttribute('custom');
2 consle.log(dataAttribute);
css DOM
1 document.querySelector('.element')
2 document.querySelector('#element')
3 document.querySelector('div')
4 document.querySelector('[name="username"]')
5 document.querySelector('div + p > span')
null
Element
NodeList
DOM
15
1 document.getElementById('id '); id
2 document.getElementsByClassName('class '); class
3 document.getElementsByTagName(' ');
4 document.getElementsByName('name ');
5 document/element.querySelector('CSS ');
6 document/element.querySelectorAll('CSS ');
7 document.documentElement; HTML
8 document.body; BODY
9 document.all[''];
DOM
parentNode childNodes firstChild lastChild nextSibling previo
usSibling
16
1 // <p id="p">...</p >
2 var p = document.getElementById('p');
3 // abc:
4 p.innerHTML = 'ABC'; // <p id="p">ABC</p >
5 // HTML:
6 p.innerHTML = 'ABC <span style="color:red">RED</span> XYZ';
7 // <p>...</p >
HTML HTML
innerText textContent
17
<div></div> innerHTML = '<span>chil
d</span>' DOM DOM
innerHTML
1 const js = document.getElementById('js')
2 js.innerHTML = "JavaScript"
3 const list = document.getElementById('list');
4 list.appendChild(js);
HTML
DOM js
18
1 const list = document.getElementById('list'),
2 const haskell = document.createElement('p');
3 haskell.id = 'haskell';
4 haskell.innerText = 'Haskell';
5 list.appendChild(haskell);
1 parentElement.insertBefore(newElement, referenceElement)
referenceElement
removeChild
1 // :
2 const self = document.getElementById('to-be-removed');
3 // :
4 const parent = self.parentElement;
5 // :
6 const removed = parent.removeChild(self);
7 removed === self; // true
19
BOM
DOM BOM
Bom window
20
window
window
moveBy(x,y)
moveTo(x,y)
resizeBy(w,h)
resizeTo(w,h)
scrollTo(x,y)
scrollBy(x,y)
window.open() url
window.open()
1 window.open('htttp://www.vue3js.cn','topFrame')
2 ==> < a href=" " target="topFrame"></ a>
window.open() window
21
window.close() window.open()
window opener
url
1 http://foouser:[email protected]:80/WileyCDA/?q=javascript#contents
location
location.reload()
true
22
navigator
navigator
23
24
history URL
URL
history.go()
1 history.go('maixaofei.com')
1 history.go(3) //
2 history.go(-1) //
history.forward()
history.back()
history.length
25
true
JavaScript
valueOf()
null undefined
26
1 let result1 = (null == undefined ); // true
NaN false
true
true
undefined null
27
1 let result1 = (null === null) //true
2 let result2 = (undefined === undefined) //true
null ==
28
1 const obj = {};
2
3 if(obj.x == null){
4 console.log("1"); //
5 }
null undefined
typeof
29
1 typeof operand
2 typeof(operand)
operand
1 typeof 1 // 'number'
2 typeof '1' // 'string'
3 typeof undefined // 'undefined'
4 typeof true // 'boolean'
5 typeof Symbol() // 'symbol'
6 typeof null // 'object'
7 typeof [] // 'object'
8 typeof {} // 'object'
9 typeof console // 'object'
10 typeof console.log // 'function'
typeof function
object
typeof if(a) a
1 if(typeof a != 'undefined'){
2 //
3 }
instanceof prototype
30
1 object instanceof constructor
object constructor
new instanceof
1 //
2 let Car = function() {}
3 let benz = new Car()
4 benz instanceof Car // true
5 let car = new String('xxx')
6 car instanceof String // true
7 let str = 'xxx'
8 str instanceof String // false
instanceof
true false
typeof instanceof
typeof instanceof
instanceof
31
typeof null
function
Object.prototype.toString
“[object Xxx]”
toString
1 function getType(obj){
2 let type = typeof obj;
3 if (type !== "object") { // typeof
4 return type;
5 }
6 // typeof object
7 return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/,
'$1');
8 }
32
1 getType([]) // "Array" typeof [] object toString
2 getType('123') // "string" typeof
3 getType(window) // "Window" toString
4 getType(null) // "Null" typeof null object toString
5 getType(undefined) // "undefined" typeof
6 getType() // "undefined" typeof
7 getType(function(){}) // "function" typeof
8 getType(/123/g) //"RegExp" toString
JavaScript
prototype
prototype
33
1 function doSomething(){}
2 console.log( doSomething.prototype );
1 {
2 constructor: ƒ doSomething(),
3 __proto__: {
4 constructor: ƒ Object(),
5 hasOwnProperty: ƒ hasOwnProperty(),
6 isPrototypeOf: ƒ isPrototypeOf(),
7 propertyIsEnumerable: ƒ propertyIsEnumerable(),
8 toLocaleString: ƒ toLocaleString(),
9 toString: ƒ toString(),
10 valueOf: ƒ valueOf()
11 }
12 }
constructor
__proto__
prototype
34
1 function Person(name) {
2 this.name = name;
3 this.age = 18;
4 this.sayName = function() {
5 console.log(this.name);
6 }
7 }
8 //
9 var person = new Person('person')
35
Person Person.prototype
Person.__proto__ anonymous
36
Function.prototype Function.__proto__ anonymous
null
__proto__
__proto__ prototype
Function
Object
Function
37
1 Object.__proto__ === Function.prototype
Object Function
Object Function
38
1 function myFunction() {
2 let inVariable = " ";
3 }
4 myFunction();//
5 console.log(inVariable); // Uncaught ReferenceError: inVariable is not defi
ned
myFunction inVariable
1 //
2 var greeting = 'Hello World!';
3 function greet() {
4 console.log(greeting);
5 }
6 // 'Hello World!'
7 greet();
39
1 function greet() {
2 var greeting = 'Hello World!';
3 console.log(greeting);
4 }
5 // 'Hello World!'
6 greet();
7 // Uncaught ReferenceError: greeting is not defined
8 console.log(greeting);
1 {
2 //
3 let greeting = 'Hello World!';
4 var lang = 'English';
5 console.log(greeting); // Prints 'Hello World!'
6 }
7 // 'English'
8 console.log(lang);
9 // Uncaught ReferenceError: greeting is not defined
10 console.log(greeting);
JavaScript
40
1 var a = 2;
2 function foo(){
3 console.log(a)
4 }
5 function bar(){
6 var a = 3;
7 foo();
8 }
9 bar()
Javascript Javascript
41
42
1 var sex = ' ';
2 function person() {
3 var name = ' ';
4 function student() {
5 var age = 18;
6 console.log(name); //
7 console.log(sex); //
8 }
9 student();
10 console.log(age); // Uncaught ReferenceError: age is not defined
11 }
12 person();
person age
43
this JavaScript
this
this
1 function baz() {
2 // baz
3 //
4
5 console.log( "baz" );
6 bar(); // <-- bar
7 }
8
9 function bar() {
10 // baz --> bar
11 // baz
12
13 console.log( "bar" );
14 foo(); // <-- foo
15 }
16
17 function foo() {
18 // baz --> bar --> foo
19 // bar
20
21 console.log( "foo" );
22 }
23
24 baz(); // <-- baz
this this
44
1 var a = 10;
2 var obj = {
3 a: 20
4 }
5
6 function fn() {
7 this = obj; // this
8 console.log(this.a);
9 }
10
11 fn();
this
person this
undefined
45
this
1 function test() {
2 console.log(this.x);
3 }
4
5 var obj = {};
6 obj.x = 1;
7 obj.m = test;
8
9 obj.m(); // 1
this
1 var o = {
2 a:10,
3 b:{
4 fn:function(){
5 console.log(this.a); //undefined
6 }
7 }
8 }
9 o.b.fn();
this b b a undefined
46
1 var o = {
2 a:10,
3 b:{
4 a:12,
5 fn:function(){
6 console.log(this.a); //undefined
7 console.log(this); //window
8 }
9 }
10 }
11 var j = o.b.fn;
12 j();
new this
1 function test() {
2 this.x = 1;
3 }
4
5 var obj = new test();
6 obj.x // 1
new this
47
1 function fn()
2 {
3 this.user = 'xxx';
4 return {};
5 }
6 var a = new fn();
7 console.log(a.user); //undefined
this
1 function fn()
2 {
3 this.user = 'xxx';
4 return 1;
5 }
6 var a = new fn;
7 console.log(a.user); //xxx
null new
1 function fn()
2 {
3 this.user = 'xxx';
4 return null;
5 }
6 var a = new fn;
7 console.log(a.user); //xxx
48
1 var x = 0;
2 function test() {
3 console.log(this.x);
4 }
5
6 var obj = {};
7 obj.x = 1;
8 obj.m = test;
9 obj.m.apply(obj) // 1
this
1 const obj = {
2 sayThis: () => {
3 console.log(this);
4 }
5 };
6
7 obj.sayThis(); // window JavaScript sayThis
this window
8 const globalSay = obj.sayThis;
9 globalSay(); // window global
this this
49
1 const button = document.getElementById('mngb');
2 button.addEventListener('click', ()=> {
3 console.log(this === window) // true
4 this.innerHTML = 'clicked button'
5 })
this window
1 Cat.prototype.sayName = () => {
2 console.log(this === window) //true
3 return this.name
4 }
5 const cat = new Cat('mm');
6 cat.sayName()
50
1 function foo() {
2 console.log( this.a );
3 }
4
5 var obj1 = {
6 a: 2,
7 foo: foo
8 };
9
10 var obj2 = {
11 a: 3,
12 foo: foo
13 };
14
15 obj1.foo(); // 2
16 obj2.foo(); // 3
17
18 obj1.foo.call( obj2 ); // 3
19 obj2.foo.call( obj1 ); // 2
51
1 function foo(something) {
2 this.a = something;
3 }
4
5 var obj1 = {
6 foo: foo
7 };
8
9 var obj2 = {};
10
11 obj1.foo( 2 );
12 console.log( obj1.a ); // 2
13
14 obj1.foo.call( obj2, 3 );
15 console.log( obj2.a ); // 3
16
17 var bar = new obj1.foo( 4 );
18 console.log( obj1.a ); // 2
19 console.log( bar.a ); // 4
>
new
1 function foo(something) {
2 this.a = something;
3 }
4
5 var obj1 = {};
6
7 var bar = foo.bind( obj1 );
8 bar( 2 );
9 console.log( obj1.a ); // 2
10
11 var baz = new bar( 3 );
12 console.log( obj1.a ); // 2
13 console.log( baz.a ); // 3
52
bar new bar(3) obj1.a n
ew bar() this
new >
JavaScript new
new Person
53
new Person
1 function Test(name) {
2 this.name = name
3 return 1
4 }
5 const t = new Test('xxx')
6 console.log(t.name) // 'xxx'
1 function Test(name) {
2 this.name = name
3 console.log(this) // Test { name: 'xxx' }
4 return { age: 26 }
5 }
6 const t = new Test('xxx')
7 console.log(t) // { age: 26 }
8 console.log(t.name) // 'undefined'
new
obj
this obj
54
1 function Person(name, age){
2 this.name = name;
3 this.age = age;
4 }
5 const person1 = new Person('Tom', 20)
6 console.log(person1) // Person {name: "Tom", age: 20}
7 t.sayName() // 'Tom'
55
new
new
new
56
call apply bind
this
this
say martin
say setTimeout
this window lucy
57
apply call bind
apply this
this this
1 function fn(...args){
2 console.log(this,args);
3 }
4 let obj = {
5 myname:" "
6 }
7
8 fn.apply(obj,[1,2]); // this obj
9 fn(1,2) // this window
call this
58
1 function fn(...args){
2 console.log(this,args);
3 }
4 let obj = {
5 myname:" "
6 }
7
8 fn.call(obj,1,2); // this obj
9 fn(1,2) // this window
this
this this
1 function fn(...args){
2 console.log(this,args);
3 }
4 let obj = {
5 myname:" "
6 }
7
8 const bindFn = fn.bind(obj); // this obj bind
59
this
bind
this
1 // bind
2 fn.bind(obj,1,2)()
3
4 // bind
5 fn.bind(obj,1)(2)
new
60
1 Function.prototype.myBind = function (context) {
2 //
3 if (typeof this !== "function") {
4 throw new TypeError("Error");
5 }
6
7 //
8 const args = [...arguments].slice(1),
9 fn = this;
10
11 return function Fn() {
12
13 //
14 return fn.apply(this instanceof Fn ? new fn(...arguments) : contex
t, args.concat(...arguments));
15 }
16 }
Javascript Javascr
ipt
window this
61
eval
62
This Binding
1 ExecutionContext = {
2 ThisBinding = <this value>, // this
3 LexicalEnvironment = { ... }, //
4 VariableEnvironment = { ... }, //
5 }
this this
null
this
arguments
63
1 GlobalExectionContext = { //
2 LexicalEnvironment: { //
3 EnvironmentRecord: { //
4 Type: "Object", //
5 //
6 outer: <null> //
7 }
8 }
9
10 FunctionExectionContext = { //
11 LexicalEnvironment: { //
12 EnvironmentRecord: { //
13 Type: "Declarative", //
14 // //
15 outer: <Global or outer function environment reference>
16 }
17 }
let const
var
1 let a = 20;
2 const b = 30;
3 var c;
4
5 function multiply(e, f) {
6 var g = 20;
7 return e * f * g;
8 }
9
10 c = multiply(20, 30);
64
1 GlobalExectionContext = {
2
3 ThisBinding: <Global Object>,
4
5 LexicalEnvironment: { //
6 EnvironmentRecord: {
7 Type: "Object",
8 //
9 a: < uninitialized >,
10 b: < uninitialized >,
11 multiply: < func >
12 }
13 outer: <null>
14 },
15
16 VariableEnvironment: { //
17 EnvironmentRecord: {
18 Type: "Object",
19 //
20 c: undefined,
21 }
22 outer: <null>
23 }
24 }
25
26 FunctionExectionContext = {
27
28 ThisBinding: <Global Object>,
29
30 LexicalEnvironment: {
31 EnvironmentRecord: {
32 Type: "Declarative",
33 //
34 Arguments: {0: 20, 1: 30, length: 2},
35 },
36 outer: <GlobalLexicalEnvironment>
37 },
38
39 VariableEnvironment: {
40 EnvironmentRecord: {
41 Type: "Declarative",
42 //
43 g: undefined
44 },
45 outer: <GlobalLexicalEnvironment>
65
46 }
47
}
Javascript undefined
Javascript
66
1 let a = 'Hello World!';
2 function first() {
3 console.log('Inside first function');
4 second();
5 console.log('Again inside first function');
6 }
7 function second() {
8 console.log('Inside second function');
9 }
10 first();
11 console.log('Inside Global Execution Context');
first
first second
second first
first
67
javascript HTML
DOM
DOM
68
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Event Bubbling</title>
6 </head>
7 <body>
8 <button id="clickMe">Click Me</button>
9 </body>
10 </html>
button
1 1.button
2 2.body
3 3.document
4 4.window
button
69
JS
DOM0
70
btn
DOM0 null
1 btn.onclick = null;
document
document
eventType
handler
71
1 var btn = document.getElementById('.btn');
2 btn.addEventListener(‘click’, showMessage, false);
3 btn.removeEventListener(‘click’, showMessage, false);
DOM
useCapture true
1 <div id='div'>
2 <p id='p'>
3 <span id='span'>Click Me!</span>
4 </p >
5 </div>
72
eventPhase
Click Me!
1 P 3
2 DIV 3
p div p
true
1 DIV 1
2 P 1
div p
document
1 attachEvent(eventType, handler)
73
1 detachEvent(eventType, handler)
click keydown
74
DOM
1 <ul id="list">
2 <li>item 1</li>
3 <li>item 2</li>
4 <li>item 3</li>
5 ......
6 <li>item n</li>
7 </ul>
1 //
2 const lis = document.getElementsByTagName("li")
3 //
4 for (let i = 0; i < lis.length; i++) {
5 lis[i].onclick = function(e){
6 console.log(e.target.innerHTML)
7 }
8 }
ul
75
1 //
2 document.getElementById('list').addEventListener('click', function (e) {
3 //
4 var event = e || window.event;
5 var target = event.target || event.srcElement;
6 //
7 if (target.nodeName.toLocaleLowerCase === 'li') {
8 console.log('the content is: ', target.innerHTML);
9 }
10 });
html input
76
1 const oBtn = document.getElementById("btn");
2 const oUl = document.getElementById("ul1");
3 const num = 4;
4
5 //
6 oUl.onclick = function (ev) {
7 ev = ev || window.event;
8 const target = ev.target || ev.srcElement;
9 if (target.nodeName.toLowerCase() == 'li') {
10 console.log('the content is: ', target.innerHTML);
11 }
12
13 };
14
15 //
16 oBtn.onclick = function () {
17 num++;
18 const oLi = document.createElement('li');
19 oLi.innerHTML = `item ${num}`;
20 oUl.appendChild(oLi);
21 };
click mousedown mouseup keydown keyup keypre
ss
focus blur
mousemove mouseout
77
JavaScript
1 function init() {
2 var name = "Mozilla"; // name init
3 function displayName() { // displayName()
4 alert(name); //
5 }
6 displayName();
7 }
8 init();
displayName()
78
1 function makeSizer(size) {
2 return function() {
3 document.body.style.fontSize = size + 'px';
4 };
5 }
6
7 var size12 = makeSizer(12);
8 var size14 = makeSizer(14);
9 var size16 = makeSizer(16);
10
11 document.getElementById('size-12').onclick = size12;
12 document.getElementById('size-14').onclick = size14;
13 document.getElementById('size-16').onclick = size16;
79
1 //
2 function getArea(width, height) {
3 return width * height
4 }
5 // 10
6 const area1 = getArea(10, 20)
7 const area2 = getArea(10, 30)
8 const area3 = getArea(10, 40)
9
10 //
11 function getArea(width) {
12 return height => {
13 return width * height
14 }
15 }
16
17 const getTenWidthArea = getArea(10)
18 // 10
19 const area1 = getTenWidthArea(20)
20
21 //
22 const getTwentyWidthArea = getArea(20)
JavaScript
80
1 var Counter = (function() {
2 var privateCounter = 0;
3 function changeBy(val) {
4 privateCounter += val;
5 }
6 return {
7 increment: function() {
8 changeBy(1);
9 },
10 decrement: function() {
11 changeBy(-1);
12 },
13 value: function() {
14 return privateCounter;
15 }
16 }
17 })();
18
19 var Counter1 = makeCounter();
20 var Counter2 = makeCounter();
21 console.log(Counter1.value()); /* logs 0 */
22 Counter1.increment();
23 Counter1.increment();
24 console.log(Counter1.value()); /* logs 2 */
25 Counter1.decrement();
26 console.log(Counter1.value()); /* logs 1 */
27 console.log(Counter2.value()); /* logs 0 */
Counter1 Counter2
81
1 function MyObject(name, message) {
2 this.name = name.toString();
3 this.message = message.toString();
4 this.getName = function() {
5 return this.name;
6 };
7
8 this.getMessage = function() {
9 return this.message;
10 };
11 }
82
JS undefined null boolean string n
umber symbol object
1 let x = y ? 1 : a;
83
84
1 Number(324) // 324
2
3 //
4 Number('324') // 324
5
6 // NaN
7 Number('324abc') // NaN
8
9 // 0
10 Number('') // 0
11
12 // true 1 false 0
13 Number(true) // 1
14 Number(false) // 0
15
16 // undefined NaN
17 Number(undefined) // NaN
18
19 // null 0
20 Number(null) // 0
21
22 // NaN( )
23 Number({a: 1}) // NaN
24 Number([1, 2, 3]) // NaN
25 Number([5]) // 5
Number
NaN
1 parseInt('32a3') //32
85
1 //
2 String(1) // "1"
3
4 //
5 String("a") // "a"
6
7 // true "true" false "false"
8 String(true) // "true"
9
10 //undefined "undefined"
11 String(undefined) // "undefined"
12
13 //null "null"
14 String(null) // "null"
15
16 //
17 String({a: 1}) // "[object Object]"
18 String([1, 2, 3]) // "1,2,3"
86
1 Boolean(undefined) // false
2 Boolean(null) // false
3 Boolean(0) // false
4 Boolean(NaN) // false
5 Boolean('') // false
6 Boolean({}) // true
7 Boolean([]) // true
8 Boolean(new Boolean(false)) // true
+ - * / %
Boolean
87
false true
1 '5' + 1 // '51'
2 '5' + true // "5true"
3 '5' + false // "5false"
4 '5' + {} // "5[object Object]"
5 '5' + [] // "5"
6 '5' + function (){} // "5function (){}"
7 '5' + undefined // "5undefined"
8 '5' + null // "5null"
1 '5' - '2' // 3
2 '5' * '2' // 10
3 true - 1 // 0
4 false - 1 // -1
5 '1' - 1 // 0
6 '5' * [] // 0
7 false / '5' // 0
8 'abc' - 1 // NaN
9 null + 1 // 1
10 undefined + 1 // NaN
88
JavaScript
89
1 function shallowClone(obj) {
2 const newObj = {};
3 for(let prop in obj) {
4 if(obj.hasOwnProperty(prop)){
5 newObj[prop] = obj[prop];
6 }
7 }
8 return newObj;
9 }
JavaScript
Object.assign
Array.prototype.slice() Array.prototype.concat()
1 var obj = {
2 age: 18,
3 nature: ['smart', 'good'],
4 names: {
5 name1: 'fx',
6 name2: 'xka'
7 },
8 love: function () {
9 console.log('fx is a great girl')
10 }
11 }
12 var newObj = Object.assign({}, fxObj);
90
1 const fxArr = ["One", "Two", "Three"]
2 const fxArrs = fxArr.slice(0)
3 fxArrs[1] = "love";
4 console.log(fxArr) // ["One", "Two", "Three"]
5 console.log(fxArrs) // ["One", "love", "Three"]
91
1 const _ = require('lodash');
2 const obj1 = {
3 a: 1,
4 b: { f: { g: 1 } },
5 c: [1, 2, 3]
6 };
7 const obj2 = _.cloneDeep(obj1);
8 console.log(obj1.b.f === obj2.b.f);// false
1 const $ = require('jquery');
2 const obj1 = {
3 a: 1,
4 b: { f: { g: 1 } },
5 c: [1, 2, 3]
6 };
7 const obj2 = $.extend(true, {}, obj1);
8 console.log(obj1.b.f === obj2.b.f); // false
1 const obj2=JSON.parse(JSON.stringify(obj1));
undefined symbol
92
1 const obj = {
2 name: 'A',
3 name1: undefined,
4 name3: function() {},
5 name4: Symbol('A')
6 }
7 const obj2 = JSON.parse(JSON.stringify(obj));
8 console.log(obj2); // {name: "A"}
93
94
1 //
2 const obj1 = {
3 name : 'init',
4 arr : [1,[2,3],4],
5 };
6 const obj3=shallowClone(obj1) //
7 obj3.name = "update";
8 obj3.arr[1] = [5,6,7] ; //
9
10 console.log('obj1',obj1) // obj1 { name: 'init', arr: [ 1, [ 5, 6, 7 ],
4 ] }
11 console.log('obj3',obj3) // obj3 { name: 'update', arr: [ 1, [ 5, 6, 7 ],
4 ] }
1 //
2 const obj1 = {
3 name : 'init',
4 arr : [1,[2,3],4],
5 };
6 const obj4=deepClone(obj1) //
7 obj4.name = "update";
8 obj4.arr[1] = [5,6,7] ; //
9
10 console.log('obj1',obj1) // obj1 { name: 'init', arr: [ 1, [ 2, 3 ], 4 ] }
11 console.log('obj4',obj4) // obj4 { name: 'update', arr: [ 1, [ 5, 6, 7 ],
4 ] }
95
96
1 (function() {
2 var a = 1;
3 function add() {
4 const b = 2
5 let sum = b + a
6 console.log(sum); // 3
7 }
8 add()
9 })()
add a = 1
1 //
2 var add = function (x,y) {
3 return x+y;
4 }
5 add(3,4) //7
6
7 //
8 var add2 = function (x) {
9 //** **
10 return function (y) {
11 return x+y;
12 }
13 }
14 add2(3)(4) //7
97
1 function foo(){
2 var a = 2;
3
4 function bar() {
5 console.log(a);
6 }
7 return bar;
8 }
9 var baz = foo();
10 baz();//2
cache
98
cache cache
func cache
+ ${} concat
99
100
101
102
1 let str = "12+23+34"
2 let arr = str.split("+") // [12,23,34]
RegExp
RegExp
103
1 let text = "cat, bat, sat, fat";
2 let result = text.replace("at", "ond");
3 console.log(result); // "cond, bat, sat, fat"
104
push()
105
pop() length
shift() length
106
splice
107
1 let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
2 numbers.indexOf(4) // 3
true false
1 const people = [
2 {
3 name: "Matt",
4 age: 27
5 },
6 {
7 name: "Nicholas",
8 age: 29
9 }
10 ];
11 people.find((element, index, array) => element.age < 28) // // {name: "Mat
t", age: 27}
108
1 let values = [1, 2, 3, 4, 5];
2 values.reverse();
3 alert(values); // 5,4,3,2,1
109
110
true
111
JavaScript
JavaScript
ajax setTimeout
112
1 console.log(1)
2
3 setTimeout(()=>{
4 console.log(2)
5 }, 0)
6
7 new Promise((resolve, reject)=>{
8 console.log('new Promise')
9 resolve()
10 }).then(()=>{
11 console.log('then')
12 })
13
14 console.log(3)
console.log(1)
new Promise
console.log(3)
setTimeout .then
113
114
115
1 console.log(1)
2 setTimeout(()=>{
3 console.log(2)
4 }, 0)
5 new Promise((resolve, reject)=>{
6 console.log('new Promise')
7 resolve()
8 }).then(()=>{
9 console.log('then')
10 })
11 console.log(3)
1 // console.log(1) 1
2 //
3 // new Promise 'new Promise'
4 // .then
5 // console.log(3) 3
6 // .then
'then'
7 // 2
async await async wait async
await
async promise
116
1 function f() {
2 return Promise.resolve('TEST');
3 }
4
5 // asyncF is equivalent to f!
6 async function asyncF() {
7 return 'TEST';
8 }
await await
await async
async
117
1 fn2 3 2
JavaScript
118
then promise2
settimeout
javaScript
Cookie
HTTP
cookie
119
cookie HTTPS
cookie cookie
cookie
cookie
Expires
1 Max-Age=604800
Domain Cookie
cookie cookie
cookie
120
cookie cookie cookie
HTML5
localStorage storage
storage
localStorage
localStorage
1 localStorage.setItem('username','cfangxu');
1 localStorage.getItem('username')
1 localStorage.key(0) //
121
1 localStorage.removeItem('username')
1 localStorage.clear()
localStorage
Cookie
sessionStorage localStorage
sessionStorage
indexedDB
Web Storage
IndexedDB
LocalStorage
JS
122
indexedDB
object store
DOM
request
indexdb Godb.js
cookie sessionStorage localStorage
localStorage ses
sionStorage cookie cookie
cookie coo
kie sessionStorage localStorage
cookie
localStorage
sessionStorage
indexedDB
123
124
125
1 const input = document.querySelector('input');
2 input.addEventListener('change', function() {
3 var file = this.files[0];
4 });
md5
126
1 var reader = new FileReader();
2 reader.readAsArrayBuffer(file);
3 reader.addEventListener("load", function(e) {
4 // 10M ,
5 var slice = e.target.result.slice(0, 10*1024*1024);
6 });
127
1 function checkFileType(type, file, back) {
2 /**
3 * type png jpg mp4 ...
4 * file input.change=> this.files[0]
5 * back callback(boolean)
6 */
7 var args = arguments;
8 if (args.length != 3) {
9 back(0);
10 }
11 var type = args[0]; // type = '(png|jpg)' , 'png'
12 var file = args[1];
13 var back = typeof args[2] == 'function' ? args[2] : function() {};
14 if (file.type == '') {
15 //
16 var imgType = [
17 'ff d8 ff', //jpg
18 '89 50 4e', //png
19
20 '0 0 0 14 66 74 79 70 69 73 6F 6D', //mp4
21 '0 0 0 18 66 74 79 70 33 67 70 35', //mp4
22 '0 0 0 0 66 74 79 70 33 67 70 35', //mp4
23 '0 0 0 0 66 74 79 70 4D 53 4E 56', //mp4
24 '0 0 0 0 66 74 79 70 69 73 6F 6D', //mp4
25
26 '0 0 0 18 66 74 79 70 6D 70 34 32', //m4v
27 '0 0 0 0 66 74 79 70 6D 70 34 32', //m4v
28
29 '0 0 0 14 66 74 79 70 71 74 20 20', //mov
30 '0 0 0 0 66 74 79 70 71 74 20 20', //mov
31 '0 0 0 0 6D 6F 6F 76', //mov
32
33 '4F 67 67 53 0 02', //ogg
34 '1A 45 DF A3', //ogg
35
36 '52 49 46 46 x x x x 41 56 49 20', //avi (RIFF fileSize fileTy
pe LIST)(52 49 46 46,DC 6C 57 09,41 56 49 20,4C 49 53 54)
37 ];
38 var typeName = [
39 'jpg',
40 'png',
41 'mp4',
42 'mp4',
43 'mp4',
44 'mp4',
128
45 'mp4',
46
'm4v',
47
'm4v',
48
'mov',
49
'mov',
50
'mov',
51
'ogg',
52
'ogg',
53
'avi',
54
];
55
var sliceSize = /png|jpg|jpeg/.test(type) ? 3 : 12;
56
var reader = new FileReader();
57
reader.readAsArrayBuffer(file);
58
reader.addEventListener("load", function(e) {
59
var slice = e.target.result.slice(0, sliceSize);
60
reader = null;
61
if (slice && slice.byteLength == sliceSize) {
62
var view = new Uint8Array(slice);
63
var arr = [];
64
view.forEach(function(v) {
65
arr.push(v.toString(16));
66
});
67
view = null;
68
var idx = arr.join(' ').indexOf(imgType);
69
if (idx > -1) {
70
back(typeName[idx]);
71
} else {
72
arr = arr.map(function(v) {
73
if (i > 3 && i < 8) {
74
return 'x';
75
}
76
return v;
77
});
78
var idx = arr.join(' ').indexOf(imgType);
79
if (idx > -1) {
80
back(typeName[idx]);
81
} else {
82
back(false);
83
}
84
85
}
86
} else {
87
back(false);
88
}
89
90
});
91
} else {
92
var type = file.name.match(/\.(\w+)$/)[1];
129
93 back(type);
94
}
95
}
1 checkFileType('(mov|mp4|avi)',file,function(fileType){
2 // fileType = mp4,
3 // file false
4 });
1 formdata.append('filename', md5code+'.'+fileType);
md5
XMLHttpRequest abort
130
AJAX
JavaScript XML
Ajax XmlHttpRequest
JavaScript DOM
131
Ajax XMLHttpRequest
HTTP XHR
Ajax
Ajax XMLHttpRequest
XMLHttpRequest open()
XMLHttpRequest send()
XMLHttpRequest onreadystatechange
HTML
132
XMLHttpRequest() XMLHttpRequest
XMLHttpRequest open()
url
async true
user
password
XMLHttpRequest send()
1 xhr.send([body])
GET
open() url
send() null
133
onreadystatechange XMLHttpRequest.
readyState
XMLHttpRequest.readyState
readyState readystatechange
XMLHttpRequest.responseText
XMLHttpRequest ajax
134
1 // ajax
2 function ajax(options) {
3 // XMLHttpRequest
4 const xhr = new XMLHttpRequest()
5
6
7 //
8 options = options || {}
9 options.type = (options.type || 'GET').toUpperCase()
10 options.dataType = options.dataType || 'json'
11 const params = options.data
12
13 //
14 if (options.type === 'GET') {
15 xhr.open('GET', options.url + '?' + params, true)
16 xhr.send(null)
17 } else if (options.type === 'POST') {
18 xhr.open('POST', options.url, true)
19 xhr.send(params)
20
21 //
22 xhr.onreadystatechange = function () {
23 if (xhr.readyState === 4) {
24 let status = xhr.status
25 if (status >= 200 && status < 300) {
26 options.success && options.success(xhr.responseText, xhr.r
esponseXML)
27 } else {
28 options.fail && options.fail(status)
29 }
30 }
31 }
32 }
135
1 ajax({
2 type: 'post',
3 dataType: 'json',
4 data: {},
5 url: 'https://xxxx',
6 success: function(text,xml){//
7 console.log(text)
8 },
9 fail: function(status){////
10 console.log(status)
11 }
12 })
136
debounce throttle
delay
137
1 function throttled2(fn, delay = 500) {
2 let timer = null
3 return function (...args) {
4 if (!timer) {
5 timer = setTimeout(() => {
6 fn.apply(this, args)
7 timer = null
8 }, delay);
9 }
10 }
11 }
138
1 function debounce(func, wait) {
2 let timeout;
3
4 return function () {
5 let context = this; // this
6 let args = arguments; // event
7
8 clearTimeout(timeout)
9 timeout = setTimeout(function(){
10 func.apply(context, args)
11 }, wait);
12 }
13 }
12 timeout = setTimeout(function () {
13 timeout = null;
14 }, wait)
15 if (callNow) {
16 func.apply(context, args)
17 }
18 }
19 else {
20 timeout = setTimeout(function () {
21 func.apply(context, args)
22 }, wait);
23 }
24 }
25 }
139
setTimeout
clearTimeout setTimeout
140
resize
141
142
offsetTop offset
clientWidth clientHeight
client
scroll
scrollWidth scrollHeight
scrollLeft scrollTop
scrollTop > 0
scrollLeft > 0
scrollLeft scrollTop
143
1 el.offsetTop - document.documentElement.scrollTop <= viewPortHeight
144
top left
145
1 function isInViewPort(element) {
2 const viewWidth = window.innerWidth || document.documentElement.clientWi
dth;
3 const viewHeight = window.innerHeight || document.documentElement.client
Height;
4 const {
5 top,
6 right,
7 bottom,
8 left,
9 } = element.getBoundingClientRect();
10
11 return (
12 top >= 0 &&
13 left >= 0 &&
14 right <= viewWidth &&
15 bottom <= viewHeight
16 );
17 }
Intersection Observer
getBoundingClientRect
1 const options = {
2 // 0 - 1
3 // 1
4 threshold: 1.0,
5 root:document.querySelector('#scrollArea') //
6 };
7
8 const callback = (entries, observer) => { ....}
9
10 const observer = new IntersectionObserver(callback, options);
146
new IntersectionObserver observer callback
threshold
callback
1 // callback
2 const callback = function(entries, observer) {
3 entries.forEach(entry => {
4 entry.time; //
5 entry.rootBounds; //
6 entry.boundingClientRect; //
7 entry.intersectionRect; //
8 entry.intersectionRatio; //
9 entry.target; //
10 });
11 };
observer.observe(target)
Html
1 <div class="container"></div>
css
147
1 .container {
2 display: flex;
3 flex-wrap: wrap;
4 }
5 .target {
6 margin: 5px;
7 width: 20px;
8 height: 20px;
9 background: red;
10 }
container
getBoundingClientRect
1 function isInViewPort(element) {
2 const viewWidth = window.innerWidth || document.documentElement.clientW
idth;
3 const viewHeight =
4 window.innerHeight || document.documentElement.clientHeight;
5 const { top, right, bottom, left } = element.getBoundingClientRect();
6
7 return top >= 0 && left >= 0 && right <= viewWidth && bottom <= viewHei
ght;
8 }
scroll
yellow
148
1 $(window).on("scroll", () => {
2 console.log("scroll !");
3 $targets.each((index, element) => {
4 if (isInViewPort(element)) {
5 $(element).css("background-color", "yellow");
6 }
7 });
8 });
scroll scroll
Intersection Observer
getYellow
.target
149
passport
passport
passport
passport
150
tieba.baidu.com map.baid
u.com baidu.com
Cookie
Web
token Coo
kie Cookie
Token
Cookie Cookie
URL
Token URL
Token Token
Token Cookie
Cookie Token
151
Session ID Token
Session ID Token L
ocalStorage LocalStorage
1 // token
2 var token = result.data.token;
3
4 // iframe iframe HTML
5 var iframe = document.createElement("iframe");
6 iframe.src = "http://app1.com/localstorage.html";
7 document.body.append(iframe);
8 // postMessage() token iframe
9 setTimeout(function () {
10 iframe.contentWindow.postMessage(token, "http://app1.com");
11 }, 4000);
12 setTimeout(function () {
13 iframe.remove();
14 }, 6000);
15
16 // iframe HTML token
localStorage
17 window.addEventListener('message', function (event) {
18 localStorage.setItem('token', event.data)
19 }, false);
152
153
sso sso
sso
154
iscroll better-scroll pulltorefresh.js
scrollTop window
155
clientHeight
scrollHeight
body
touchstart e.touches[0].pageY
touchmove 0
translateY
Html
156
1 <main>
2 <p class="refreshText"></p >
3 <ul id="refreshContainer">
4 <li>111</li>
5 <li>222</li>
6 <li>333</li>
7 <li>444</li>
8 <li>555</li>
9 ...
10 </ul>
11 </main>
touchstart
touchmove
1 _element.addEventListener('touchmove', function(e) {
2 // e.touches[0].pageY
3 _transitionHeight = e.touches[0].pageY - _startPos; //
4
5 if (_transitionHeight > 0 && _transitionHeight < 60) {
6 _refreshText.innerText = ' ';
7 _element.style.transform = 'translateY('+_transitionHeight+'px)';
8
9 if (_transitionHeight > 55) {
10 _refreshText.innerText = ' ';
11 }
12 }
13 }, false);
157
touchend
1 _element.addEventListener('touchend', function(e) {
2 _element.style.transition = 'transform 0.5s ease 1s';
3 _element.style.transform = 'translateY(0px)';
4 _refreshText.innerText = ' ...';
5 // todo...
6
7 }, false);
better-scroll
1 <div id="position-wrapper">
2 <div>
3 <p class="refresh"> </p >
4 <div class="position-list">
5 <!-- -->
6 </div>
7 <p class="more"> </p >
8 </div>
9 </div>
use
158
1 import BScroll from "@better-scroll/core";
2 import PullDown from "@better-scroll/pull-down";
3 import PullUp from '@better-scroll/pull-up';
4 BScroll.use(PullDown);
5 BScroll.use(PullUp);
BetterScroll
159
1 let pageNo = 1,pageSize = 10,dataList = [],isMore = true;
2 var scroll= new BScroll("#position-wrapper",{
3 scrollY:true,//
4 click:true,// click true
5 pullUpLoad:true,//
6 pullDownRefresh:{
7 threshold:50,// pullingDown
8 stop:0//
9 }
10 });
11 //
12 scroll.on("pullingDown",pullingDownHandler);
13 //
14 scroll.on("scroll",scrollHandler);
15 //
16 scroll.on("pullingUp",pullingUpHandler);
17
18 async function pullingDownHandler(){
19 dataList=[];
20 pageNo=1;
21 isMore=true;
22 $(".more").text(" ");
23 await getlist();//
24 scroll.finishPullDown();//
25 scroll.refresh();// dom
26 }
27 async function pullingUpHandler(){
28 if(!isMore){
29 $(".more").text(" ");
30 scroll.finishPullUp();//
31 return;
32 }
33 pageNo++;
34 await this.getlist();//
35 scroll.finishPullUp();//
36 scroll.refresh();// dom
37 }
38 function scrollHandler(){
39 if(this.y>50) $('.refresh').text(" ");
40 else $('.refresh').text(" ");
41 }
42 function getlist(){
43 //
44 let result=....;
45 dataList=dataList.concat(result);
160
46 //
47
if(result.length<pageSize) isMore=false;
48
// dataList html
49
}
better-scroll
wrapper
wrapper
DOM refresh()
finishPullUp() finishPullDown()
better-scroll click
click:true
161
JavaScript
1 const re = /\d+/g;
RegExp
\ \\
162
{1,}
{0,1}
163
s .
u unicode
y sticky
164
1 var re = /pattern/flags;
2 var re = new RegExp("pattern", "flags");
bbb
b bb
\d{1,3} \d{1,3}
\d{1,3}? \d{1,3}
165
() beyond{3} d (beyond){3} b
eyond
test exec
166
String
regexp g
index input str
regexp g
g null
167
1 let str = "I love JavaScript";
2
3 let result = str.match(/HTML/);
4
5 console.log(result); // null
-1
search
g
168
1 const reg1=/javascript/i;
2 const reg2=/javascript/ig;
3 console.log('hello Javascript Javascript Javascript'.replace(reg1,'js'));
4 //hello js Javascript Javascript
5 console.log('hello Javascript Javascript Javascript'.replace(reg2,'js'));
6 //hello js js js
g regexp.exec(str) str.match(regexp)
g regexp.exec(str)
regexp.lastIndex regexp.lastIndex
regexp.lastIndex
169
true/false
1 var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
2 const isvalid = patrn.exec(s)
url
170
1 const protocol = '(?<protocol>https?:)';
2 const host = '(?<host>(?<hostname>[^/#?:]+)(?::(?<port>\\d+))?)';
3 const path = '(?<pathname>(?:\\/[^/#?]+)*\\/?)';
4 const search = '(?<search>(?:\\?[^#]*)?)';
5 const hash = '(?<hash>(?:#.*)?)';
6 const reg = new RegExp(`^${protocol}\/\/${host}${path}${search}${hash}$`);
7 function execURL(url){
8 const result = reg.exec(url);
9 if(result){
10 result.groups.port = result.groups.port || '';
11 return result.groups;
12 }
13 return {
14 protocol:'',host:'',hostname:'',port:'',
15 pathname:'',search:'',hash:'',
16 };
17 }
18
19 console.log(execURL('https://localhost:8080/?a=b#xxxx'));
20 protocol: "https:"
21 host: "localhost:8080"
22 hostname: "localhost"
23 port: "8080"
24 pathname: "/"
25 search: "?a=b"
26 hash: "#xxxx"
search hash
171
1 function execUrlParams(str){
2 str = str.replace(/^[#?&]/,'');
3 const result = {};
4 if(!str){ //
5 return result;
6 }
7 const reg = /(?:^|&)([^&=]*)=?([^&]*?)(?=&|$)/y
8 let exec = reg.exec(str);
9 while(exec){
10 result[exec[1]] = exec[2];
11 exec = reg.exec(str);
12 }
13 return result;
14 }
15 console.log(execUrlParams('#'));// {}
16 console.log(execUrlParams('##'));//{'#':''}
17 console.log(execUrlParams('?q=3606&src=srp')); //{q: "3606", src: "srp"}
18 console.log(execUrlParams('test=a=b=c&&==&a='));//{test: "a=b=c", "":
"=", a: ""}
172
1 //
2 var array = [0, 1, 2, 3]
3 for(let i = 0; i < array.length; i++) {
4 array[i] = Math.pow(array[i], 2)
5 }
6
7 //
8 [0, 1, 2, 3].map(num => Math.pow(num, 2))
173
1 let double = value=>value*2;
174
1 const forEach = function(arr,fn){
2 for(let i=0;i<arr.length;i++){
3 fn(arr[i]);
4 }
5 }
6 let arr = [1,2,3];
7 forEach(arr,(item)=>{
8 console.log(item);
9 })
forEach
175
1 const once = (fn)=>{
2 let done = false;
3 return function(){
4 if(!done){
5 fn.apply(this,fn);
6 }else{
7 console.log(" ");
8 }
9 done = true;
10 }
11 }
1 let fn = (x,y)=>x+y;
curry
176
1 //
2 const curry = function(fn){
3 return function curriedFn(...args){
4 if(args.length<fn.length){
5 return function(){
6 return curriedFn(...args.concat([...arguments]));
7 }
8 }
9 return fn(...args);
10 }
11 }
12 const fn = (x,y,z,a)=>x+y+z+a;
13 const myfn = curry(fn);
14 console.log(myfn(1)(2)(3)(1));
1 function afn(a){
2 return a*2;
3 }
4 function bfn(b){
5 return b*3;
6 }
7 const compose = (a,b)=>c=>a(b(c));
8 let myfn = compose(afn,bfn);
9 console.log( myfn(2));
177
1 const compose = (...fns)=>val=>fns.reverse().reduce((acc,fn)=>fn(acc),val);
compose
178
XSS Web
XSS cookie
179
url
"><script>alert('XSS');</script>
<script>alert('XSS');</script>
cookie
XSS
180
XSS
181
5 < 7 5 < 7
escapeHTML() 5 < 7
5 < 7
5 < 7
182
1 <!-- -->
2 < a href=" ">1</ a>
3
4 <script>
5 // setTimeout()/setInterval()
6 setTimeout("UNTRUSTED")
7 setInterval("UNTRUSTED")
8
9 // location
10 location.href = 'UNTRUSTED'
11
12 // eval()
13 eval("UNTRUSTED")
post
183
1 <form action="http://bank.example/withdraw" method=POST>
2 <input type="hidden" name="account" value="xiaoming" />
3 <input type="hidden" name="amount" value="10000" />
4 <input type="hidden" name="for" value="hacker" />
5 </form>
6 <script> document.forms[0].submit(); </script>
POST
csrf
184
token
Sql Sql
185
web
186
C
1 char * buffer;
2 buffer = (char*) malloc(42);
3
4 // Do something with buffer
5
6 free(buffer);
malloc free
JavaScript
187
1 var m = 0,n = 19 // m,n,add()
2 add(m, n) // a, b, c
3 console.log(n) // a,b,c
4 function add(a, b) {
5 a++
6 var c = a + b
7 return c
8 }
[1, 2, 3, 4] arr
1 arr
1 arr = null
188
1 function foo(arg) {
2 bar = "this is a hidden global variable";
3 }
this
1 function foo() {
2 this.variable = "potential accidental global";
3 }
4 // foo this window
5 foo();
id DOM someRes
ource someResource
189
1 function bindEvent() {
2 var obj = document.createElement('XXX');
3 var unused = function () {
4 console.log(obj, ' obj obj ');
5 };
6 obj = null; //
7 }
DOM
addEventListener removeEventListen
er
190
JavaScript
1 class Car{
2 constructor(color,speed){
3 this.color = color
4 this.speed = speed
5 // ...
6 }
7 }
1 //
2 class Truck extends Car{
3 constructor(color,speed){
4 super(color,speed)
5 this.Container = true //
6 }
7 }
191
1 class Truck extends Car{
2 constructor(color,speed){
3 super(color,speed)
4 this.color = "black" //
5 this.Container = true //
6 }
7 }
JavaScripy
192
1 function Parent() {
2 this.name = 'parent1';
3 this.play = [1, 2, 3]
4 }
5 function Child() {
6 this.type = 'child2';
7 }
8 Child1.prototype = new Parent();
9 console.log(new Child())
s1 play s2
call Parent
193
1 function Parent(){
2 this.name = 'parent1';
3 }
4
5 Parent.prototype.getName = function () {
6 return this.name;
7 }
8
9 function Child(){
10 Parent1.call(this);
11 this.type = 'child'
12 }
13
14 let child = new Child();
15 console.log(child); //
16 console.log(child.getName()); //
194
1 function Parent3 () {
2 this.name = 'parent3';
3 this.play = [1, 2, 3];
4 }
5
6 Parent3.prototype.getName = function () {
7 return this.name;
8 }
9 function Child3() {
10 // Parent3()
11 Parent3.call(this);
12 this.type = 'child3';
13 }
14
15 // Parent3()
16 Child3.prototype = new Parent3();
17 //
18 Child3.prototype.constructor = Child3;
19 var s3 = new Child3();
20 var s4 = new Child3();
21 s3.play.push(4);
22 console.log(s3.play, s4.play); //
23 console.log(s3.getName()); // 'parent3'
24 console.log(s4.getName()); // 'parent3'
Par
ent3
Object.create
195
1 let parent4 = {
2 name: "parent4",
3 friends: ["p1", "p2", "p3"],
4 getName: function() {
5 return this.name;
6 }
7 };
8
9 let person4 = Object.create(parent4);
10 person4.name = "tom";
11 person4.friends.push("jerry");
12
13 let person5 = Object.create(parent4);
14 person5.friends.push("lucy");
15
16 console.log(person4.name); // tom
17 console.log(person4.name === person4.getName()); // true
18 console.log(person5.name); // parent4
19 console.log(person4.friends); // ["p1", "p2", "p3","jerry","lucy"]
20 console.log(person5.friends); // ["p1", "p2", "p3","jerry","lucy"]
Object.create
196
1 let parent5 = {
2 name: "parent5",
3 friends: ["p1", "p2", "p3"],
4 getName: function() {
5 return this.name;
6 }
7 };
8
9 function clone(original) {
10 let clone = Object.create(original);
11 clone.getFriends = function() {
12 return this.friends;
13 };
14 return clone;
15 }
16
17 let person5 = clone(parent5);
18
19 console.log(person5.getName()); // parent5
20 console.log(person5.getFriends()); // ["p1", "p2", "p3"]
Object.create
197
1 function clone (parent, child) {
2 // Object.create
3 child.prototype = Object.create(parent.prototype);
4 child.prototype.constructor = child;
5 }
6
7 function Parent6() {
8 this.name = 'parent6';
9 this.play = [1, 2, 3];
10 }
11 Parent6.prototype.getName = function () {
12 return this.name;
13 }
14 function Child6() {
15 Parent6.call(this);
16 this.friends = 'child5';
17 }
18
19 clone(Parent6, Child6);
20
21 Child6.prototype.getFriends = function () {
22 return this.friends;
23 }
24
25 let person6 = new Child6();
26 console.log(person6); //{friends:"child5",name:"child5",play:[1,2,3],__pro
to__:Parent6}
27 console.log(person6.getName()); // parent6
28 console.log(person6.getFriends()); // child5
198
1 class Person {
2 constructor(name) {
3 this.name = name
4 }
5 //
6 // Person.prototype.getName = function() { }
7 // getName() {...}
8 getName = function () {
9 console.log('Person:', this.name)
10 }
11 }
12 class Gamer extends Person {
13 constructor(name, age) {
14 // “this” super()
15 super(name)
16 this.age = age
17 }
18 }
19 const asuna = new Gamer('Asuna', 20)
20 asuna.getName() //
babel extends
199
Object.create
extends
false
200
JavaScript Number Number IEEE754
javaScript
201
10000000011 10111
javascript
1 // 0.1 0.2
2 0.00011001100110011001100110011001100110011001100110011010 +
3 0.0011001100110011001100110011001100110011001100110011010 =
4 0.0100110011001100110011001100110011001100110011001100111
5
6 // 0.30000000000000004
false
x=0.1 0.1
2^53=9007199254740992 9.007199254740992
toPrecision(16)
1 .10000000000000000555.toPrecision(16)
2 // 0.1000000000000000 0.1
0.1 0.1
202
1 0.1.toPrecision(21) = 0.100000000000000005551
9007199254740992
2^1024 - 1
2^1024 Infinity
(2^53, 2^63)
(2^53, 2^54)
(2^54, 2^55)
bignumber.js
203
1 parseFloat(1.4000000000000001.toPrecision(12)) === 1.4 // True
+-*/ toPrecision
1 /**
2 *
3 */
4 function add(num1, num2) {
5 const num1Digits = (num1.toString().split('.')[1] || '').length;
6 const num2Digits = (num2.toString().split('.')[1] || '').length;
7 const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
8 return (num1 * baseNum + num2 * baseNum) / baseNum;
9 }
Math.js BigDecimal.js
204
pow(x, n) x n
1 function pow(x, n) {
2 let result = 1;
3
4 // x result n
5 for (let i = 0; i < n; i++) {
6 result *= x;
7 }
8 return result;
9 }
1 function pow(x, n) {
2 if (n == 1) {
3 return x;
4 } else {
5 return x * pow(x, n - 1);
6 }
7 }
pow(x, n)
205
1 if n==1 = x
2 /
3 pow(x, n) =
4 \
5 else = x * pow(x, n - 1)
pow n == 1
pow(2, 4)
pow(2, 4) = 2 * pow(2, 3)
pow(2, 3) = 2 * pow(2, 2)
pow(2, 2) = 2 * pow(2, 1)
pow(2, 1) = 2
206
1 function factorial(n) {
2 if (n === 1) return 1;
3 return n * factorial(n - 1);
4 }
5
6 factorial(5) // 120
n
O(n)
207
1 function sumArray(arr, total) {
2 if(arr.length === 1) {
3 return total
4 }
5 return sum(arr, total + arr.pop())
6 }
208
1 let obj = {
2 a: '1',
3 b: {
4 c: '2',
5 D: {
6 E: '3'
7 }
8 }
9 }
10 //
11 let obj = {
12 a: '1',
13 b: {
14 c: '2',
15 d: {
16 e: '3'
17 }
18 }
19 }
20
21 //
22 function keysLower(obj) {
23 let reg = new RegExp("([A-Z]+)", "g");
24 for (let key in obj) {
25 if (obj.hasOwnProperty(key)) {
26 let temp = obj[key];
27 if (reg.test(key.toString())) {
28 // temp obj
29 temp = obj[key.replace(reg, function (result) {
30 return result.toLowerCase()
31 })] = obj[key];
32 //
33 delete obj[key];
34 }
35 //
36 if (typeof temp === 'object' || Object.prototype.toString.call
(temp) === '[object Array]') {
37 keysLower(temp);
38 }
39 }
40 }
41 return obj;
42 };
209
210