Initial javaScript hunting

Chapter 1 Introduction to JavaScript


1.ECMAScript Core Language Functions
2.DOM Document Object Model
3.BOM Browser Object Model

Chapter 2 Using JavaScript in HTML

1. <script>element

Defer indicates that the script will not affect page construction during execution, that is, it will delay execution until the entire page is rendered.When the browser encounters defer script parsing, it downloads the script asynchronously, but does not stop the work of dom rendering until the page rendering is complete, then executes the script, and multiple encounters are loaded sequentially.

Async browsers download files asynchronously immediately, unlike defer, which executes immediately when the download is complete and blocks the DOM rendering, so async's script is best not to manipulate dom.Since it is executed immediately after download, there is no guarantee that multiple loads will be sequenced

2.<noscript>
   <p>I won't support it script Of h5</p>
</noscript>

Chapter III Basic Concepts of JavaScript

3. Language->Arabic numerals->binary (ASCII American Standard Code for Information Exchange Unicode code code extends from ASCII character set.)

4.Unicode is an encoding scheme. Unicode is designed to solve the limitations of the traditional character encoding scheme. It sets a uniform and unique binary encoding for each character in each language to meet the requirements of text conversion and processing across languages and platforms.There are three implementations of Unicode encoding, utf-8,utf-16,utf-32, in which UTF-8 takes one to four bytes, utf-16 two or four bytes, and UTF-32 four bytes.

base64 is also a character
The charCodeAt() method returns the Unicode encoding of a character at a specified location.This return value is an integer between 0 and 65535.
fromCharCode(72,69,76,76,79)//hello accepts a specified Unicode value and returns a string

var iNum = 10;
alert(iNum.toString(2));	//Output "1010"
alert(iNum.toString(8));	//Output "12"
alert(iNum.toString(16));	//Output "A"

The parseInt() method also has a base mode that converts binary, octal, hexadecimal, or any other binary string to an integer.The base is specified by the second parameter of the parseInt() method, so to resolve hexadecimal values, you need to call the parseInt() method as follows:

var iNum1 = parseInt("10", 2);	//Return 2
var iNum2 = parseInt("10", 8);	//Return 8
var iNum3 = parseInt("10", 10);	//Return 10
var iNum1 = parseInt("AF", 16);	//Return 175

new Blob([uInt8Array], { type: "audio/wav" });
Array is an Array made up of ArrayBuffer, ArrayBufferView, Blob, DOMString, etc., or a mixture of other similar objects, which will be put into the Blob.DOMStrings are encoded as UTF-8.

  const bytes = window.atob(base.split(',')[1]);
                const ab = new ArrayBuffer(bytes.length);
                const ia = new Uint8Array(ab);
                for (let i = 0; i < bytes.length; i++) {
                    console.log(bytes.charCodeAt(i), 'bytes.charCodeAt(i)')
                    ia[i] = bytes.charCodeAt(i);
                }
                blob = new Blob([ab], { type: 'image/png' });
            
             var binary =""
             var bytes = new Uint8Array(buffer);
                var len = bytes.byteLength;
                for (var i = 0; i < len; i++) {
                  binary += String.fromCharCode(bytes[i]);
                }

canvas.toBlob(callback, type, encoderOptions); callback function callback type format encoderOptions picture quality

5. Attribute Name Hump Naming
6.a. The first identifier is the letter underscore_Dollar Dollar Dollar
b. Other Character Underline_Dollar Sign$Number
7. Strict Mode
"use strict"
8. Keyword Reserved Words

break    do       instanceof  typeOf
case     else     new         var
catch    finally  return      void
continue for      switch      while
debugger function  this       with
default  if        throw
delete   in         try
abstract  enum      int  short
boolean   export    interface
byte      extends    long
char      final      native
class     float      package
const     goto       private
debugger  implements protected
double    import     

Fifth Edition
Non-strict mode

class  enum  extends  super
const  export import

Strict mode

implements  package  public
interface   private   static
let         protected  yield

9. Out of range isFinite{}

Returns true if the number is a finite number (or can be converted to a finite number).Otherwise, false is returned if the number is NaN (not a number), or if it is a positive or negative infinite number.

10. Numeric Judgment
The isNaN() function checks whether its parameter is a non-numeric value.

Returns true if the parameter value is NaN or a non-numeric value such as string, object, undefined, or false otherwise.(false for numbers that can be converted by hermits)

Number()  All
parseInt() //string
parseFloat()//string
console.log(isNaN(10))//false
console.log(isNAN('a'))//true

11.String type is a character sequence of 0 or more Unicode characters

String() All
 toSting() divided by null undefined
 Escape Character
 \n Line Break
 \t Tabulation
 \b Spaces
 \r Enter
 \f Paper Feed
 \Slash
 \'Single Quote  
\"Double Quotes
 \x nn represents a character in hexadecimal code n n (where n is o~F)
u nnn denotes Unicode in hexadecimal code n n n (where n is 0~F)u03a3 denotes

12.obect

var o=new Object
constructor create object o Constructor Object
hasOwnProperty o.hasOwnProperty ('name)Detect if the current instance is not in the prototype chain
isPrototypeOf(object) Detect whether it is a prototype object for an instance
propertyIsEnumerable()Determine if it can be enumerated for-inergodic
toLocalString()Returns the string local representation of the object
toString() Returns the string of the object
valueOf()  Return object string toString Agreement (Use first valueOf stay toString)

13.Unary Operator
+Hermit to (character-based)
-*/Hermit Conversion to (Number-based) ++-
++ A and a++.
-b and b-

14. Bit Operators (underlying operations for js)

var a=18;
var b=-a
//Bitwise Not~
var a=18
var b=~a-1
//Bitwise and&
var a=25&3
console.log(a)//1


Only one bit of the binary code corresponding to 25 and 3 is 1, while the other bits are all equal to 0 so 1

Bitwise or |
var a=25|3
console.log(a)//27

Bitwise XOR^
var a=25^3
console.log(a)//26

Move < Left
 var a=3//11 equal to binary
 Var b=a< 5 //equal to 1100000 96
 Move Right
 var a=96; //equal to 1100000	
var b=a>>5 //11          3
 Unsigned Right Shift (Ordered as Unordered for Positive Numbers)
var a=96//equal to 1100000 a.toString(2),b.toString(2)
Var b=a>>5//equal to 1

Unordered Symbol Right Shift (Negative)

15. Boolean Operators
a. Logical NOT! Booleran() equivalent!!
b. Logical and & & The first returns false, the first returns true and the second (find false)
c.Logic or || di First returns false Second First returns true Second (Find True)
16. Additive Operators
+Hermit to (character-based)
-*/%Hermit Converts to (Number-based) ++-
++ A and a++.
-b and b-
17. Relational Operators

<Less Than>Greater Than<=Less Than Equal>=Greater Than Equal 
1. Perform a number comparison if both are numbers
 2. Compare character encoding between two strings
 3. Comparison of Number and Character to Number
 4. Object calls valueof for comparison
 5. Boolean Conversion Comparison

18. Commas are side-by-side declarations

var a=0,b=1;

19.do-while

var i=0;
do{
i+=2
}while(i<10)
console.log(i)

var i=0;
while(i<10){
i+=2
}

for(var i=0;i<4;i++){
}

lable can be used to identify for loops

loop:
for(var i=0;i<5;i++){
}
 var arr = [[1, 2, 3], [2, 3, 4], [3, 5, 6]]
        let arr2=[]
        for (var i = 0; i < arr.length; i++) {
            let arr1 = arr[i]
            for (var j = 0; j < arr1.length; j++) {
                if (arr1[j] == 3) {
                    arr2.push(arr1[j])
                    break
                }
                console.log(arr1[j])
            }
            break
        }
        console.log(arr2,'arr1[j]')
break End cycle
continue Break

20.with statement

let obj={
name:'zs',
age:18
}
with(obj){
var name=name;
var age=age
}

Warning: Strict mode error is not recommended
21.switch

var num=0
switch(1){
case 1: num=2
break;
case 1:
case 2: 
 num=2
break;
default:33
}

Note: the switch statement uses unequal identical symbols 10 and'10'
22. Functions

Function (){} anonymous function
 function (){return 12} return value anonymous function
 function a(){} declares a function
 function a(){return 12} return value declaration function
 argument accepts parameters
 Function parameters are all passed by value

Chapter IV Scope Variable Memory

23. Basic Data Reference Data Type
a. Basic data types do not dynamically (on the stack) add attributes (deep copies are independent of each other)
b. Reference data types (in the heap) can dynamically add attributes (shallow copies interact)

24. Type Detection
Basic type typeOf
Reference type:

     Mode 1
        let arr = [1, 2, 3]
        let obj = {
            name: 'zs',
            age: 18
        }
        console.log(arr.constructor=='Object')
        console.log(obj.constructor=='Array')
      //Mode 2
        let arr = [1, 2, 3]
        let obj = {
            name: 'zs',
            age: 18
        }
        console.log(arr instanceof Array);//true. 
        console.log(obj instanceof Object);//true. 
     //Mode 3
        let arr = [1, 2, 3]
        let obj = {
            name: 'zs',
            age: 18
        }
      Object.prototype.toString.call(arr ));//[object Array]
      Object.prototype.toString.call(obj ));//[object Object]
     //Mode 4
     ypeOf obj==object&&JSON.Stringfly(obj).slice(0,1)=='{'
     //Mode 5
     ypeOf obj==object&&Array.isarray()
        

Note: All reference types are instances of Object

25. Block-level Scope

1.var elevates a variable by declaring it first and then complex
 2.let generation scope
 3. Query identity lookup along scope chain (proximity principle)

26. Reference data type
Objects are stored in the heap (duplicate addresses, store data) to store data transfer
Array stores ordered data New Array(10) empty array detection array with length 10Array.isArray()

27. Objects have toLocaleString() toString() valueOf()
Array:

      let arr=[1,2,3]
      console.log(arr.toLocaleString()) //1,2,3
      console.log(arr.toString())//1,2,3
      console.log(arr.valueOf())//[1, 2, 3]
      arr.join()//1,2,3

Stack method for arrays
Push (plus) pop (after deletion) unshift (plus) shift (minus before)
Queue Method
Array reordering
reverse() sort()

 var arr=[1,3,5,7,2,4,6]
     console.log(arr.sort((n,o)=>{
         console.log(n,o,'xxx')
         return o-n
     })
     //[7, 6, 5, 4, 3, 2, 1]

concat merge slice intercept

let arr=[]
arr.concat('a',[1,2])

let arr1=[1,2,3,4,5]
console.log(arr1.slice(-2,-1))//[4]
console.log(arr1.slice(0,1))//[1]

splice

let arr=[1,2,3,4,5,6]
//deleteArr.splice(0,2) arr [3,4,5,6]
//insertArr.splice(0,0,a) arr[a,1,2,3,4,5,6]
//replaceArr.splice(0,2,a,b) arr[a,b,3,4,5,6]

Bit method
indexOf() lastIndexOf()
Iteration method

every() All for each iteration
 some() a conditional stop
 filter() filter iterates through all
 map() keeps the original array operation iterating through all
 forEach() for loop iterates through all

Reduction method

reduce() iterates through all left->right
 reduceRight() iterates over all right->left

Chapter V Types of References


object

  var obj1 = {
            name: 'lis',
            age: 19,
            toLocaleString: function () {
                return this.name
            },
            toString: function () {
                return this.age
            }
        }
        console.log(arr.toLocaleString()) //[object Object]
        console.log(arr.toString())//[object Object]
        console.log(arr.valueOf())//{name: "zs", age: 18}

28. Time Object Date
See https://blog.csdn.net/qq_42374676/article/details/106399679
29. Regular Matching

Literal Quantity Declaration
//g Match Global
//i Ignore case
//m Multiline Mode
//gi matching is global case insensitive
//Characters in regular representations are escaped 
RegExp('cat','g')

var a='abcd'
/abc/.exec(a)//["abc", index: 0, input: "abcd", groups: undefined]
/abc/.test(a)
console.log(RegExp.$1)
[http://www.regular-expressions.info/tools.html](http://www.regular-expressions.info/tools.html)

30. Function declaration

function a(){} //Function variable promotion
let a=function(){} //No variable promotion
let a=new Function('x',"return x*2")

You can pass function bodies as functions

function a(b,x){
}
a(function b(){},x)

Function Properties

arguments this
//Recursive function
function a(x){
 x++
 if(x>5){
 return 
 }else{
 arguments.callee()
}
}
//this points to the problem in which running environment this points to who
    window.color='red';
    var o={color:'blue'}
    function a(){
        console.warn(this.color)
    }
    a()//red
    o.a=a
    o.a() //blue
    -----------------------------
 function a(){
   console.log(this) //window
             }
box.onclick=function(){
     console.log(this)//box
}

length prototype of function

function a(x){}
console.log(a.length)//1 parameter
a.prototype.obj={

}

Non-inherited method call apply bind

function sum(num1,num2){
 return num1+num2
}
function callSum1(num1,num2){
 return sum.apply(this,arguments)
}
function clasSum2(num1,num2){
 return sum.apply(this,[num1,num2])
}
console.log(callSum1(10,10))//20
console.log(clasSum2(10,10))//20
//Borrow Outside------------------
    function a(x,y){
         return x+y
     }
     function b(){

     }
     console.log(a.call(b,10,20))
bind binding---------------------
function a(){console.log(this.name)}
var obj={name:'zs'}
var obj1=a.bind(obj)
obj1()

32. Basic Packaging Types

String Number Boolean
//Background automatically generates the corresponding string number boolean base type when it is executed 
String Number Boolean The basic wrapper type lets it own the properties and methods of the object and destroy it immediately after operation
        let a = 'a' //String
        console.log(typeof a)
        console.log(a instanceof String)//false
        let b = String('b')//String
        console.log(typeof b)
        console.log(b instanceof String)//false
        let c = new String('c')
        console.log(typeof c)           // Object
        console.log(c instanceof String)// Object Method
        toString()  LocaltoString() valueOf()
        var d='abed'
        d.charAt(2)//'e'return character
        d.charCodeAt(2)//'101'character encoding
        //Character concat 
        var e='abcd'
        e.concat('efg')//abcdefg
        slice(x,y) x Indexes y Indexes  substr(x,length) x Indexes length length substring(x,y)x Indexes y Indexes (x,y Not negative and can swap locations)
        var f='abcde'
        f.slice(-2)//de
        f.substr(-2,2)//de
        f.substring(2,0)//ab
        //Location Method indeOf(x,start) lastIndeOf(x,start)//start position of the character retrieved by x
        trim() Clear all nonstandard spaces trimLeft() trimRight()
        toUpperCase() toLocaleUpperCase() International Environmental Use toLocaleUpperCase()
        let a='abc'
        a.toUpperCase() //ABC
        toLowerCase() toLocaleLowerCase()
        let b='ABC'
        b.toLowerCase()//abc
        b.toLocaleLowerCase()//abc
        match()//Regular pipe
        var text = 'cat,bat,sat,fat'
        console.log(/.at/.exec(text));
        console.log(text.match(/.at/));
        search()//Regular or String
        var str='ABCde'
        str.search('d')// 3
        replace(x,y)//x string or regular y substitution character or function
        var aa='cat,bat,sat,fat'
        aa.replace('at','ond')//cond bat sat fat
        aa.replace(/at/g,'ond')//cond bond sond fond
        

      var text='cat,bat,sat,fat'
      text.replace(/(.at)/g,'word($1)') //'word (cat),word (bat),word (sat),word (fat)'

     function htmlEscape(text){
        return text.replace (/[<>"&]/,function(match,pos,origintext){
           switch(match){
           case "<":
          return "&lt"
           case ">":
          return "&gt"
          case "&"
         return "&amp"
         case "\"":
        return "&quot"
       }
       })
     }
   let bb="<p class=\"greeting\">hello word</p>"
   htmlEscape(bb)//&lt;p class=&quot;greeting;&gt;hello word &lt;/p&gt

   split(x,num)//String Split x String Regular num Number of Split
   console.log(str.split(','))// ["red", "blue", "green", "yellow"] 
   console.log(str.split(',', 2))//["red", "blue"]
   localeCompare()string comparison
   var color="yellow"
   color.localeCompare('brick')//1 //brick before yello
   color.localeCompare('yellow')//0
   color.localeCompare('zoo')//-1 //zoo after yello
   formCharCode()Method and charCodeAt()Reciprocal operation
   String.formCharcode(104,101,108,111)//hello
      
   Number  boolean Ditto
   toFixed() Keep decimal places
   toExponential() Ways to preserve scientific counting

33. Single built-in object
Global global

Methods: isNan(), isFinite(), parseInt(), parseFolat(), encodeURI()
, encodeURIComponent(), eval()JavaScript parser (called in time) to prevent code injection

Attributes:

Re-globalized objects in web browsers are window s and global in node s'js
34.Math built-in mathematical functions

var max=Math.max(3,54,32,16)
console.log(max)//54
Math.ceil(25.9)//26
Math.floor(25.9)//25
Math.round(25.9)//26
Math.random()//Random number 0-1 
1reach10Numeric value Math.floor(Math.rondom()*10+1)
2reach10Value between Math.floor(Math.rondom()*9+2)
function selectFrom(lowervalue,uppervarlue){
 var choices=uppervarlue-lowervalue+1
 return Math.floor(Math.random()*choices+lowervalue)
}

Chapter VI Object-oriented


35. Object-oriented
Objects are divided into data property access properties
1. Data Properties
Location where a data attribute contains a data value Adds, deletes, or modifies the location
Configgurable delete delete and all States cannot modify default true
Enumerable for-in Traversal Enumeration Default true
Writable indicates whether the property default true can be modified
value indicates that this number defaults to undefined

Modifying these properties providesObject.defineProperty()

var per={}
Object.defineProperty(per,'name',{
 writable:false,
 value:'zs'
})
console.log(per.name)//zs
per.name='ls'
console.log(per.name)//zs
----------------------------------
var per={
age:18
}
Object.defineProperty(per,'name',{
 Enumerable:false,
 value:'zs'
})
for(var key in per){
console.log(key) //age
}
--------------------------------
let per={}
Object.defineProperty(per,'name',{
     configurable:false,//All cannot modify Writable to false Enumerable false
     value:'zs'
   })
     console.log(per.name) //zs
     per.name='ls'
     console.log(per.name)//zs

2. Access Properties
configurable: Indicates whether the object can be added or deleted. The default is true
enumerable indicates whether default true can be enumerated
Gett Read Properties Function
set write property function

var book={
 _year:2004,
 edition:1
}
Object.defineProperty(book,'year',{
 get:function(){
 return this._year
},
set:function(newValue){
if(newValue>2004){
 this._year=newValue;
 this.edition+=newValue-2004
}
}
})
console.log(book)
book.year=2005;
console.log(book.edition)//2
------------------------------------------
defineProperties
 var book = {}
        Object.defineProperties(book, {
            _year: {
                value: 2004,
                writable: true
            },
            edition: {
                value: 1,
                writable: true
            },
            year: {
                get: function () {
                    return this._year
                },
                set: function (newValue) {
                    if (newValue > 2004) {
                        this._year = newValue;
                        this.edition += newValue - 2004
                        console.log(this.edition, 'this.edition')
                    }
                }
            }
        })
        console.log(book)
        book.year = 2005;
        console.log(book.edition)//2
        -------------------------------------------------
        let o={
            foo:'zs'
            }
     Object.getOwnPropertyDescriptor(o, "foo");
        // {
        //     configurable: true
        //     enumerable: true
        //     value: "zs"
        //     writable: true
        // }

36. Factory Mode

function createPerson(name,age,job){
 var o=new Object()
 o.name=name;
 o.age=age;
 o.job=job
 o.sayName=function(){
   console.log(this.name)
}
return o
}
var per1=createPerson('zs',18,'student')
var per2=createPerson('lis',18,'student')

Is it an object type that solves the repetitive disadvantage
37. Constructor Construction

function Person(name,age,job){
  this.name=name;
  this.age=age;
  this.job=job;
  this.sayName=function(){
  console.log(this.name)
}
}
var per=new Person('zs',18,'stendent')
var per2=new Person('lis',19,'stendent')
console.log(per.constructor==Person) //true
console.log(per instanceof Object)//true
console.log(per instanceof Person)//true

Tags: encoding Javascript ascii Attribute

Posted on Mon, 15 Jun 2020 21:51:23 -0400 by jscruggs