• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Basic syntax of JS in JavaScript series

King Wang

1 月 3, 2022

JavaScript Series of JS introduction / Basic grammar

01 JavaScript introduction

JavaScript It’s object-based and event driven , Script language with security performance

Common misconceptions about : We usually think JavaScript And Java There’s a connection , As a matter of fact ,JavaScript Except in grammar Java, The rest of it doesn’t matter .


JavaScript Key points in the development process

  • 1995 year , Netscape Brendan Eich It only took 10 It took days to design JavaScript Language .
  • 1997 year ,ECMA The organization has customized JavaScript The standard of language , go by the name of ECMAScript standard , It’s also ECMAScript The first edition of the standard .
  • ECMAScript 6 standard ( abbreviation ES6) Already in 2015 year 6 Officially released in .

JavaScript Implementation principle of

  • JavaScript Is a single thread scripting language , No compilation required , Explain and execute .JS You don’t have to run it in a browser , As long as there is JS The engine can , The most typical example is NodeJS, Using Google’s v8 engine , bring JS Run completely out of browser . When the browser reloads the document , First of all, we need to correct HTML To analyze , The browser is parsing HTML When you file ,“ From top to bottom ” load , Parsing and rendering during loading . During parsing , If an external resource is requested , Such as images 、CSS、iconfot etc. , These request processes are asynchronous , Does not affect the HTML Continue loading and parsing of documents . Encountered during document loading JS file ,HTML The document immediately suspends the rendering thread ( Load parse render synchronously ), After suspend , Wait until the JS After the file is loaded and the parsing is finished , To recover HTML Rendering thread of document . because JS It may change DOM structure , The most obvious example is document.write. That means : stay JS Before execution , All subsequent downloads of resources may not be necessary or meaningful , This is the same. JS The root cause of blocking subsequent resource downloads , therefore , Development process , Often JS Put the code in HTML At the end of the document .
  • JS The execution mechanism of is a main thread + A task queue . The synchronization task is the task executed on the main thread , Asynchronous tasks are tasks placed in the task queue . In the main thread are synchronization tasks , In the execution stack, the stack is executed , Asynchronous tasks are first handled by the corresponding modules, such as Timer modular , It must wait for the trigger conditions such as time to arrive ,callback Will be placed in the task queue , Once the tasks in the execution stack are completed , It will go to the task queue to execute the various items in the queue callback.callback queue The middle finger is “ Task queue ”, It can also be understood as message queuing ,“ news ” It can be understood as : Callback functions added when registering asynchronous tasks . It should be noted that : If the synchronous task in the execution stack is not completed, the asynchronous task in the task queue will not be executed callback Of , Even if it’s over time .

02 JavaScript Basic grammar

JavaScript Grammar and Java Language is similar to , Each statement is marked with ; end , Use… For statement block {...}. however ,JavaScript It is not mandatory to add… At the end of each statement ;, The browser is responsible for executing JavaScript The engine of the code will automatically add… At the end of each statement ;. Give Way JavaScript The engine automatically semicolons in some cases will change the semantics of the program , Results in inconsistent results with expectations

JavaScript The core syntax in consists of variables 、 data type 、 Array 、 Operation symbol 、 Control statement 、 notes 、 Input / Output 、 Grammatical conventions make up


  • Variable
var// Keywords used to declare variables
// Declare variables before assigning values
var x;
x=5;
// Declare and assign variables at the same time
var x=5;
// Variables can be used without declaration , But this method is easy to make mistakes
x=5;
// Variable itself type is not fixed , therefore JavaScript It's dynamic language
var s=1;
s="abc";

  • data type

    JavaScript The data types in are :undefined null number boolean string Array Object

    undefined : Variable has no initial value , It's only useful to determine if a function parameter is passed .
    null : Represents a null value , And undefined The values are equal . It and 0 And empty strings '' Different ,0 It's a number ,'' The length is 0 String , and null Express “ empty ”.
    number : JavaScript Don't distinguish between integers and floating-point numbers , Unified use Number Express
    boolean : ture / false
    string : Single quote ' Or double quotes " Any text enclosed .
    Array : JavaScript The array of can include any data type
    Object : JavaScript Object is a set of keys - An unordered set of values , Keys are all string types , Value willing is any data type .
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <script>
    var str = "JavaScript";
    var num = 10;
    var u;
    var arr=[1,2,3,str];
    var date = new Date();
    // Output at console
    console.log(typeof str);
    console.log(typeof num);
    console.log(typeof u);
    console.log(typeof arr);
    console.log(typeof date);
    </script>
    </body>
    </html>
    

  • String type

    • JavaScript The string of is used '' or "" The enclosed characters indicate . If ' It’s also a character , Then you can use "" Cover up , But if the string contains both ' Contain, " You need to use escape characters \ To mark .

    • Template string : To connect multiple strings , It can be used + Connection No . If there are many variables that need to be connected , use + The number is more troublesome ,ES6 Added a template string , use ${ Variable name } Express , Can automatically replace variables in string .

    • Common methods :

      • charAt(index) : Returns the specified location string
      • indexOf(str,index) : Find the first occurrence of a specified string in the string
      • substring(index1,index2): Return at specified index index1 and index2 String between ,[index1,index2)
      • split(str) : Split a string into an array of strings

  • Array

    • How to create an array :

      • var arr = [1,2,3 ];

      • var arr =new Array(5);

        arr[0]=1;

        arr[1]=3;

      • var arr = new Array(1,2,3);

    • Array common methods :

      • attribute length: Sets or returns the number of elements in an array
      • join() : Put all the elements of the array into a string , Delimit by passed in delimiters
      • sort() : Sort the array
      • push() : Add one or more elements to the end of the array , Return to the new length

  • Program instance :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var str="apple,banana,orange,watermelon,peach";
var arr=str.split(",");
console.log("====== adopt split Split into arrays ========")
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[3]);
console.log(arr[4]);
console.log("======= adopt join Turn into string========");
var str1 = arr.join("-");
console.log(str1);
console.log("======== adopt push Additive elements ===============")
arr.push("strawburry");
console.log(arr)
</script>
</head>
<body>
</body>
</html>

  • Operator

    • && Operation is with operation , Only for true,&& The result is true
    • || Operation is or is , As long as one of them is true,|| The result is true
    • ! Operation is not operation , It’s a monocular operator , hold true become false,false become true
    • The comparison operators are :> >= < <= == It should be noted that == Will automatically convert the data type and then compare , A lot of times , It’s going to get very weird results , and === Data types are not automatically converted , If the data types are not consistent , return false, If the same , Compare again .
    • An equal comparison of floating-point numbers : To compare whether two floating-point numbers are equal , Only the absolute value of their difference can be calculated , See if it is less than a certain threshold .
    Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true
    

  • Logic control statement
    • if Conditional statements
    • switch Multi branch statement
    • for、while Loop statement
    • for-in( In fact, it’s equivalent to Java Enhancement cycle in for( : )in amount to :)

  • Break the loop
    • break; Out of the loop
    • continue; Jump out of a cycle

  • notes
    • Single-line comments ://
    • Multiline comment :/*… */

  • Pop up tips
    • alert(“ Prompt information ”)
    • prompt(“ Prompt information ”,“ The default information of the input box ”)

  • Grammatical conventions
    • The code is case sensitive
    • Variable , Names of objects and functions
      • JS Keywords in lowercase
      • Built in objects start with uppercase letters
      • The name of an object is usually lowercase
      • Method naming rules and Java identical
    • A semicolon

发表回复