当前位置:网站首页>JS quick start (I)
JS quick start (I)
2022-07-07 08:01:00 【Illusory private school】
Python Wechat ordering applet course video
https://edu.csdn.net/course/detail/36074
Python Actual quantitative transaction financial management system
https://edu.csdn.net/course/detail/35475
Catalog * Javascript Quick start ( One )
- Naming rules for variables
- Variables and constants
- data type
- Operator
- Implicit type conversion
- Conditional branch
- loop
- Ternary operator
- function
- Object structure
- Built-in objects
- timer
Javascript Quick start ( One )
Naming rules for variables
- Variable names cannot start with numbers or some special characters
- Variable names cannot be keywords ,eg:for,var,function,let····
- Don't start variable names with underscores
- The recommended naming form is “ Lowercase hump nomenclature ”, Used to group multiple words together , Lowercase the first letter of the whole name, then capitalize the first character of the remaining word ,eg:myAge
- Variable naming depends on the meaning of the name
Naming examples
// Correct naming
age
myAge
init
finalOutputValue
audio1
// Wrong and irregular naming
1a_12
MYAGE
var
Document
skjfndskjfnbdskjfb
Variables and constants
Variable
stay JS You need to use keywords to declare variables in
- The old version :
var
( All are global variables ) - The new version :let ( You can declare local variables )
ps: there let stay ECM6 Available in the , It may not work properly in earlier versions ,pycharm If an error is reported when using the above keywords js Version has no choice 6
We need to customize the settings
// Variable examples
var name = 'Hammer'
let name = 'Hammer'
Constant
stay JS You also need keywords to declare constants in
- keyword :
const
const pi = 3.14
// Constant once declared , It can't be changed , Variables can be changed to
data type
JS There are six data types
Numerical type :Number
var n = 100
var pi = 3.14
- There is another kind. NaN, It's not a number (Not a Number)
Common methods :
// Convert data type : Character to number
// Method 1 :parseInt( Keep the whole number ) parseFloat( Keep decimals )
parseInt() //NaN
parseInt('') //NaN
···
parseInt("123") // return 123, At this time, the data type is number
parseInt("ABC") // return NaN,NaN Property is a special value that represents a non numeric value . This property indicates that a value is not a number .
parseFloat("123.456") // return 123.456
// Method 2 :Number
Number('123') // 123
Number('123ABC') //NaN
character string :String
var str = "Hammer";
var str1 = 'ze';
//es6 New definition string , You can write multiline strings with backquotes
var str2 = ` I
Love
learn
JS`;
// Format output ( Function of template string )
var name = 'Hammer'
var age = 18
`my name is ${name} my age is ${age} `
Common methods :
ps: String splicing is recommended
+
Method name | effect | Example | result |
---|---|---|---|
charAt() | Gets the character at the specified position | ‘abcd’.charAt(2) | c |
indexOf() | Retrieves the first occurrence of the specified string value in the string | ‘abcd’.indexOf(‘a’) | 0 |
lastIndexOf() | Query the position of the string to be searched for the first time in the original string from back to front ( Indexes ), Return if not found -1 | ‘abcdabc’.lastIndexOf(‘a’) | 4 |
search() | Retrieves the substring specified in the string , Or retrieve the substring that matches the regular expression | ‘abcd’.search(‘c’) | 2 |
match() | Retrieves the specified value from the string , Or find a match for one or more regular expressions | ‘abcdabc’.match(‘a’) | [‘a’, index: 0, input: ‘abcdabc’] |
substring() | String interception method , It can take two parameters , They are the start position and the end position to intercept , It will return a new string | ‘abcdabc’.substring(1, 4) | bcd |
slice() | And substring() The method is very similar , The two parameters it passes in also correspond to the start position and the end position respectively . And the difference is ,slice() Parameters in can be negative values | ‘abcdabc’.slice(1, 4) | bcd |
replace() | Used for string replacement , It can take two parameters , The former is the substring to be replaced , The latter is the replacement text | ‘abcd’.replace(‘a’, ‘A’) | Abcd |
split() | To divide a string into an array of strings | ‘abcd’.split(’’) | [‘a’, ‘b’, ‘c’, ‘d’] |
toLowerCase() | You can convert uppercase letters in a string to lowercase | ‘Abcd’.toLowerCase() | abcd |
toUpperCase() | You can convert lowercase letters in a string to uppercase | ‘Abcd’.toUpperCase() | ABCD |
Boolean type :Boolean
var is1 = true;
var is2 = false;
Undefined type :Undefined
Undefined means that you only declare that you don't define , No value , The norm is default
var a;
console.log(a);
//undefined
Empty type :Null
var timer = null;
console.log(timer);
object type :Object
label 、 Array 、 object 、Math··· All object types
Array
var a =[123,'ABC'];
a[0] // 123, similar python The index value of the list
typeof a //'object'
Common methods :
Method | explain |
---|---|
.length | Size of array |
.push(ele) | The tail element |
.pop() | Get the tail element |
.unshift(ele) | Header insert element |
.shift() | The head removes elements |
.slice(start, end) | section |
.reverse() | reverse |
.join(seq) | Concatenate array elements into strings |
.concat(val, …) | Linked array |
.sort() | Sort |
.forEach() | Pass each element of the array to the callback function |
.splice(a,b,c) | Remove elements , And add new elements to the array ,a Subscript subscript ,b Represents the number of deleted elements ,c Represents the newly added element |
.map() | Returns a new array of values processed by an array element call function |
indexOf( Subelement ) | Query child elements from an array , Returns the subscript , If there is no child element to query, return -1 |
//forEach() Example , Function as parameter is called callback function
arry.forEach(function(item,index){
// Code body
})
ietm: Each value of the array
index: Subscript
var n = [1,2,3,4]
n.forEach(function(item,index){
console.log(item,index)
})
sort() It should be noted that , It also needs to write callback functions
//sort() Sort the array directly , May not get the desired result
var arr = [0,-55,-58,12,33,6,55,7]
console.log(arr.sort())
//[-55, -58, 0, 12, 33, 55, 6, 7]
// Such a result is deviated from the ideal output , It should be written like this
//a,b Represents two adjacent elements , If the return value is greater than 0, Just exchange ab The order of the positions , To achieve the effect of sorting
arry.sort(function(a,b){
return a-b;
})
arr.sort(function(a,b){
return a-b
})
console.log(arr)
Math object
Common methods
Method | explain |
---|---|
floor() | Rounding down |
ceil() | Rounding up |
round() | rounding |
max() | Maximum |
min() | minimum value |
random() | random number , The scope is [0,1), Left closed right away |
pow() perhaps ** | Idempotent |
sqrt() | Square root |
abs() | The absolute value |
Methods of outputting data types
typeof [ Variable ]
- It should be noted that , The data type of empty type belongs to
object
- NaN The meaning is Not a Number, But its data type is
number
Operator
JavaScript Comparison operators are used in logical statements , To determine whether variables or values are equal , return true or false; Logical operators are used to determine the logic between variables or values
Comparison operations
We assume that num = 5, The comparison operators are explained in the following table :
Operator | describe | Example | result |
---|---|---|---|
== | Weak is equal to ( Equal value is enough ) | num6num’5‘ | falsetrue |
=== | Strong is equal to ( Values and types are equal ) | num=5num=’5‘ | truefalse |
!= | It's not equal to | num != 7 | true |
!== | Values are not equal or types are not equal | num !== 5 | false |
> | Greater than | num > 9 | false |
< | Less than | num < 9 | true |
>= | Greater than or equal to | num >= 8 | false |
<= | Less than or equal to | num <= 7 | true |
ps:=
Is assignment operator
Logical operators
We assume that num = 5, Logical operators are explained in subscripts :
Operator | describe | Example | result |
---|---|---|---|
&& | And | (num%2==1 && num>1) | true |
or | |||
! | Not | !(num%2==0) | true |
Arithmetic operation
Arithmetic operators are relatively simple :
+
、-
、*
、/
、%
、++
、--
Namely : Add 、 reduce 、 ride 、 except 、 Remainder 、 Self increasing 、 Self reduction
- It should be noted that :++a and a++ The difference between
- ++a It means self increment before assignment
- a++ It means to assign values first and then increase automatically
Implicit type conversion
JS Existing characteristics , For example, when adding strings and numbers , Will convert numbers into strings , Then splice it with another string ;
var num1 = '123'
var num2 = 12
var num3 = num1 + num2
console.log(num3)
// result :'12312'
Subtract strings and numbers 、 ride 、 In addition to the operation , And size comparison , Will convert a string to a number , And again Calculate or compare with another number
var num1 = '10'
var num2 = 1
var num3 = num1-num2
console.log(num3)
// result :9
Convert various values to Boolean values
- Numbers 0, An empty string "",null,undefined When converted to Boolean value, it is false
- Not 0 Numbers , When a non empty string is converted to a Boolean value, it is true
- Any array ( Even empty arrays ), Any object ( Even empty objects ) When converted to Boolean value, it is true
var a = 0
if (a) {
console.log('hello')
} else {
console.log('world')
}
//world
Case study
var a = true
var b = 2
var c = a*b
console.log(c)
//2
/* there true Will be converted into 1 Substitution operation */
Conditional branch
- if Branch
- switch Branch
if Branch
Basic grammatical structure
// Single branch
if( Conditions ){
// Code body
}
// Double branch
if ( Conditions 1){
// Code body
}else if( Conditions 2){
// Code body
}
// Multiple branches
if( Conditions 1){
// Code body
}else if( Conditions 2){
// Code body
}else{
// Code body
}
switch Branch
Basic grammatical structure
switch (expression) {
case value1:
// When expression The result of value1 When the match , Execute this statement
break; case value2:
// When expression The result of value2 When the match , Execute this statement
break;
...
case valueN:
// When expression The result of valueN When the match , Execute this statement
break;
default:
// If expression With the above value Values don't match , Execute this statement
break;
}
Example :
var expr = 'Hammer'
switch (expr) {
case 'Hammer':
console.log('I am Hammer');
break;
case 'Jason':
console.log('I am Jason');
break;
case 'Hans':
console.log('I am Hans')
default:
console.log('sorry,this is nothing!')
}
Example :
var a = 8
if (a>7) {
a=3
}
if (a>4) {
a=5
}
console.log(a) //3
// analysis : First a=8, Greater than 7, So will 3 Assign a value to a, Now? a=3, below a>4 For false , So don't execute , So finally a by 3
loop
for loop
for How to use the cycle
- for: Traversing code blocks multiple times
- for/in: Traverse object properties
Format
for ( sentence 1; sentence 2; sentence 3) {
// Block of code to execute
}
- sentence 1 In circulation ( Code block ) Before you start
- sentence 2 Define operating cycle ( Code block ) Conditions
- sentence 3 It's going to cycle ( Code block ) To execute after each execution
Example
for (var i=0;i<10;i++) {
console.log(i);
}
//0 1 2 3 7 8 9
var arr = [11, 22, 33, 44, 55]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i])
}
// 11 22 33 44 55
var obj = {name:"tom", gender:"man", age:32}
for (var key in obj) {
// Print key
console.log(key)
// Print value
console.log(obj[key])
}
// Execution results
name
tom
gender
man
age
32
while loop
var i = 0;
while (i < 10) {
console.log(i);
i++;
}
//0 1 2 3 7 8 9
Ternary operator
stay python in , The ternary operator is like this :
Format : ' Set up output content ' if conditional else ' Not established output '
res = ' Go to work ' if 1>2 else ' rest '
# Obviously, the result is rest
stay js The middle trinocular operator is like this :
Format : conditional ? ' Set up output content ':' Do not set up output content '
res = 1>2 ? ' Go to work ':' rest '
// The result is the same as above
function
stay JS Function is defined by declaration in , Keywords are
function
and python Mediumdef
similar
function keyword
structure
function name( Parameters 1, Parameters 2,···){
// Code block
return Return value
}
//name Is the function name
//return It's not necessary , No, return Words , Function will return undefined
Example
function pri(){
console.log(' A simple example ,hello')
}
pri() // A simple example ,hello
function add1(a, b) {
return a + b;
}
var res = add1(1,2)
console.log(res) // 3
function add2(a, b) {
a + b;
}
var res = add2(4, 5)
console.log(res) // undefined
When the function is called , The parameters given during the call and the parameters set during the definition will be bound in turn . If you call The number of given parameters is not enough , Then the unbound parameter in the function body will be assigned as undefined
function foo(a, b) {
console.log(b)
}
foo(4) // Expected output :undefined
foo(4,8) // Expected output :8
Expressions define functions
var func = function name ( Parameters 1, Parameters 2···){
// Code block
}
Example
var f = function foo(v){
return v;
}
// call , Call
f()
// If you use foo() The called will report an error
Arrows define functions
ES6 Allowed in “ arrow ”(=>) Defined function
var f = v => v;
expression Parameters Return value
// Equate to
var f = function foo(v){
return v;
}
arguments attribute
We can not specify the number of parameters , Use arguments To get the number of arguments , Represents the current parameter list ;
function add(){
var sum = 0;
for (var i=0;i<arguments.length;i++){ // Traverse
sum+=arguments[i]
}
return sum
}
var n = add(1,2,3,4,5,6)
console.log(n) //21
Anonymous functions
- Callback function
var add = function(a,b){
return a+b;
}
console.log(add(1,2))
Self executing functions
You don't need to call yourself to execute
(function(a,b,c){
console.log(a+b+c)
})(1,2,3) // Pass the reference in brackets
Recursive function
The function finally calls itself
// If the random number is not greater than ten, it will be printed all the time
function shown(){
var n = rand(0,12)
if (n>10){
return // End function
}else{
console.log(n)
shown()
}
}
shown()
function rand(min,max){
return Math.round(Math.random()*(max-min)+min);
}
// use setTimeout Realization setInterval
function interval(){
setTimeout(function(){
alert(' Recursive function ')
interval()
},1000)
}
interval()
// Equate to
setInterval(
function(){
alert(' Recursive function ')
},1000)
Object structure
JS The commonly used data type in is array ( above ) And object structure , The object structure is similar python Dictionary in , Also with
key:value
Exhibition
// Definition
var info = {
name:'Hammer',
age:18,
gender:'man',
city:' shijiazhuang '
}
// visit , modify
// Method 1
info.name
info.name = 'Ze'
// Method 2
info['age']
// Add attribute
info.car = ' BMW '
// Delete attribute
delete info.car
Traverse , Use for/in
var obj = {name:"tom", gender:"man", age:32}
for (var key in obj) {
// Print key
console.log(key)
// Print value
console.log(obj[key])
}
// Execution results
name
tom
gender
man
age
32
stay js Point method can be used in , Output the value of the object , So for python Dictionaries are not allowed , Write a method to realize
class MyDict(dict):
def \_\_getattr\_\_(self, item):
return self.get(item)
def \_\_setattr\_\_(self, key, value):
self[key] = value
res = MyDict(name='Hammer',age=18)
print(res.name)
res.xxx = 123 # add to key,value
print(res.xxx)
print(res)
Serialization deserialization
How does the front and back end realize data interaction , such as python Data types and js There's a difference , Then a translator is needed for front-end and back-end interaction ”json“, To do this task
# python in
import json
json.dumps() # serialize
json.loads() # Deserialization
JSON.stringify() // serialize
JSON.parse() // Deserialization
/*
If at present js There is a Boolean value in true It needs to be sent to... Based on the network python Program and let python Convert to Boolean How to operate
1. stay js Use in JSON.stringify() Serialized into json Format string
2. Send to based on network python Program ( Auto Code )
3.python receive Decode and deserialize
*/
Built-in objects
If you need to use built-in objects , You need keywords
new
# python Built in modules are used in
import time
time.time() # Get the timestamp
# js Using built-in objects in
new date() # Get the timestamp
Date object
var d = new Date()
d
// Sat Feb 12 2022 16:54:41 GMT+0800 ( China standard time )
d.toLocaleDateString()
// '2022/2/12'
d.toLocaleString()
// '2022/2/12 16:54:41'
d.getDay()
// 6
d.getHours()
// 16
regexp object
- The way 1:
var reg1 = new RegExp("^[a-zA-Z][a-zA-Z0-9]{5,11}");
- The way 2:
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}/;
When regular matching is used here , We need to pay attention to
Global matching rule
// The end of the regular expression does not add g It means that the matching is successful , Add g Represents a global match
var reg = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/g
reg.test('hammer666')
true
reg.test('hammer666')
false
reg.test('hammer666')
true
reg.test('hammer666')
false
// There will be a global match lastIndex attribute , Match success stops at the end of the character to be matched , So the second match is false, The third match will re match
reg
/^[a-zA-Z][a-zA-Z0-9]{5,9}$/g
reg.test()
//true
reg.test()
//false
reg.test()
//true
reg.test()
//false
// Check the parameters , The default is undefined
var un = /undefined/
un.test()
//true
match matching
timer
JS There are two kinds of timers
- setTimeout (fn,time): Delay time after , Do it once fn
- setInterval (fn,time): every other time after , Do it once fn
- time The time of is in milliseconds
setTimeout Example , Only perform the timing task once
setInterval Mission
Of course, there is the establishment of timing tasks , There is a way to clear the timing task
- clearTimeout: Clear timed task
- clearInterval: Clear timed task
var timer = null;
var count = 0;
timer = setInterval(function(){
count ++;
if(count ==10 ){
clearInterval(timer)
}
console.log(' Remember to turn off the timing task ~')
},2000)
Case study
There are many small programs , It will count how many days are left before the new year , Or how many days have you been in love , In fact, it's very simple to realize
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> New year countdown title>
<style>
*{
margin:0;
padding: 0;
}
html,body{
height: 100%;
}
.bg{
height: 100%;
background-color: #999999;
background-image: url("https://imgapi.cn/bing.php");
background-size: cover;
background-position: center center;
}
.shadow{
height: 100%;
background-color: rgba(0,0,0,.5);
overflow: hidden;
}
p{
height: 40px;
line-height: 40px;
font-size: 36px;
color: white;
text-align: center;
}
style>
head>
<body>
<div class = 'bg'>
<div class = 'shadow'>
<p style="margin-top: 300px"> I'm in love p>
<p style="margin-top: 20px">
<span id="day">0span> God
p>
div>
div>
body>
<script>
// Get tag
var spanDay = document.getElementById('day')
var timer = null;
timer = setInterval(function (){
var date1 = new Date("2018-09-02")
var date2 = new Date("2022-02-12")
var n = date2.getTime() - date1.getTime()
n /=1000; // second
var day = n / (60*60*24) // Days
spanDay.innerHTML = parseInt(day)
},1000)
script>
html>
边栏推荐
- Chip information website Yite Chuangxin
- 通信设备商,到底有哪些岗位?
- Pytorch parameter initialization
- nacos
- 2022 recurrent training question bank and answers of refrigeration and air conditioning equipment operation
- Leetcode 90: subset II
- Implementation of replacement function of shell script
- JSON data flattening pd json_ normalize
- [UTCTF2020]file header
- Leetcode 43 String multiplication (2022.02.12)
猜你喜欢
misc ez_ usb
[guess-ctf2019] fake compressed packets
Li Kou interview question 04.01 Path between nodes
Jenkins remote build project timeout problem
Wechat applet data binding multiple data
numpy中dot函数使用与解析
[webrtc] M98 screen and window acquisition
2022制冷与空调设备运行操作复训题库及答案
Cnopendata list data of Chinese colleges and Universities
Thinkcmf6.0安装教程
随机推荐
Mysql高低版本切换需要修改的配置5-8(此处以aicode为例)
Force buckle 144 Preorder traversal of binary tree
Numbers that appear only once
Operation suggestions for today's spot Silver
You Li takes you to talk about C language 6 (common keywords)
Pytorch parameter initialization
C语言二叉树与建堆
Pytest+allure+jenkins installation problem: pytest: error: unrecognized arguments: --alluredir
Thinkcmf6.0安装教程
Binary tree and heap building in C language
Linux server development, MySQL index principle and optimization
PHP exports millions of data
微信小程序基本组件使用介绍
Explore dry goods! Apifox construction ideas
Rust Versus Go(哪种是我的首选语言?)
[UTCTF2020]file header
[SUCTF 2019]Game
SQL优化的魅力!从 30248s 到 0.001s
Idea add class annotation template and method template
misc ez_ usb