程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

JS of front-end language (compare Python quick start)

編輯:Python

Yesterday's review

  • float
  • location
  • overflow
  • transparency
  • Modal frame

Summary of today's content

  • Variables and constants
  • Basic data type
  • Data type built-in methods
  • function
  • Common built-in objects
  • BOM And DOM operation

Detailed content

1. Variables and constants

# 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 Recommended let)
"""
JavaScript The variable name of can be used _, Numbers , Letter ,$ form , Cannot start with a number .
Declare variables using var Variable name ; To make a declaration
""" # stay JS You also need to use keywords to declare constants in
const >>> Declare a real constant # How to create variables
var name = 'jason'
let name = 'jason01' # How to create constants
const pi = 3.14 # To write js Code location
1.pycharm Provided js file
2. Directly use the programming environment provided by the browser
""" After opening the browser page Right mouse button Select Check Just select as shown in the figure below """ """
pycharm If an error is reported when using the above keywords explain js Version has no choice 6
We need to customize the settings settings>>>l&f>>>js Pictured
"""

2. Basic data type

# python Basic data type 
int integer 、float floating-point 、str character string 、list list 、dict Dictionaries 、bool Boolean value 、tuple Tuples 、set aggregate # js Basic data type
number、string、boolean、undefined、object() # View data type
python Use in type()
js Use in typeof

3.number type

# JavaScript Don't distinguish between integer and floating point , There is only one type of number 
var a = 12.34;
var b = 20;
var c = 123e5; // 12300000
var d = 123e-5; // 0.00123 # There is another kind. NaN, It's not a number (Not a Number)
parseInt Turn integer
parseFloat To floating point
parseInt("123") // return 123
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
"""NaN It's a numerical type It means It's not a number """

4.string type

# How to define character types 
1. Single quotation marks ''
2. Double quotes ""
3. The quotation marks ``
var s1 = `
jason teacher
tony teacher
kevin teacher
` # stay js The splicing of strings in is recommended + Number # Format output ( Function of template string )
var name1 = 'jason'
var age = 18
`my name is ${name1} my age is ${age} `

5.boolean type

# stay python The first letter of boolean type in uppercase 
True False # stay js Boolean types in are all lowercase
true false
""( An empty string )、0、null、undefined、NaN All are false

6.null And undefined type

# null The value is empty , It is usually used when a variable needs to be specified or cleared 
Such as name=null; # undefined Indicates when a variable is declared but not initialized ( Only variables are declared , But there is no assignment )
The default value for this variable is undefined
And when there is no clear return value for the function , And back again undefined
'''null It means that we have run out of toilet paper undefined It means there is no toilet paper Pictured '''

7. The array type of the object

"""
JavaScript Everything in is an object (Object): character string 、 The number 、 Array 、 function ... Besides ,JavaScript Allow custom objects Objects are just special data types with properties and methods
""" # The function of an array object is : Use a separate variable name to store a series of values Be similar to Python List in li.splice(2,1) # The first parameter is the starting position ( Determine the position according to the index value ) The second parameter is the number of deleted elements ( No, the default is 1)

8. Operator

# + - * / % ++ -- > >= < <= != == === !==
var x=10;
var res1=x++;
var res2=++x; res1;
10
res2;
12 # there x++ and ++x Assignment expression
x++ Will give first res1 Assign a value and then increase it by itself 1 operation here res1 by 10 x by 11
and ++x We will do the increment operation first and then assign the value here x by 11 res2 by 12 # In the comparison operator
== Weak is equal to # The data type will be automatically converted to the same state
=== Strong is equal to # Data types are not automatically converted
1 == "1" // true Weak is equal to
1 === "1" // false Strong is equal to # Logical operators ( One-to-one correspondence )
python in
and or not
js in
&& || !

9. Process control

# if Judge 
1.python in
if Conditions :
Code executed after the condition is established
else:
Code executed when the condition does not hold 2.js in
Situation 1 :
if( Conditions ){
Code executed after the condition is established
}else{
Code executed when the condition does not hold
}
Situation two :
if( Conditions 1){
Conditions 1 Code executed after establishment
}else if( Conditions 2){
Conditions 2 Code executed after establishment
}else{
Conditions are not tenable, the code executed
} # switch
var day = new Date().getDay();
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
default:
console.log("...")
} # for loop
for( Starting value ; The loop condition ; What to do after each cycle ){
for Loop body code
} for (var i=0;i<10;i++) {
console.log(i);
} # practice : How to use for Loop out each element in the array
var l1 = [111,222,333,444,555,666]
for(let i=0;i<l1.length;i++){
console.log(l1[i])
} # while loop
while( The loop condition ){
Loop body code
} var i = 0;
while (i < 10) {
console.log(i);
i++;
}

10. Ternary operator

# stay python in 
res = ' having dinner ' if 18 > 10 else ' Drink lots of water ' # stay js in
res = 18 > 10 ? ' having dinner ':' Drink lots of water ' var a = 1;
var b = 2;
var c = a > b ? a : b // The order of ternary operation here is to write the judgment condition first a>b If the rewrite condition is true, the returned value is a, If the condition is not true, the value returned is b Ternary operations can be nested
var a=10,b=20;var x=a>b ?a:(b=="20")?a:b;x10

11. function

# stay python in 
def Function name ( Parameters 1, Parameters 2,...):
''' Function Comments '''
Function body code
return Return value # stay js in
function Function name ( Parameters 1, Parameters 2,...){
// Function Comments
Function body code
return Return value
}
"""
arguments Parameters All incoming data can be obtained
Also support return And anonymous functions function add(a,b){
console.log(a+b);
console.log(arguments.length);
console.log(arguments[0]);//arguments It is equivalent to including all the parameters passed in and out , Here is the first element 1
}
add(1,2) Output :
3
2
1
""" # Arrow function
var f = v => v;
Equivalent to the following :
var f = function(v){
return v;
} # practice :
var city = "BeiJing";
function f() {
var city = "ShangHai";
function inner(){
var city = "ShenZhen";
console.log(city);
}
inner();
} f(); // The output is ?
ShenZhen var city = "BeiJing";
function Bar() {
console.log(city);
}
function f() {
var city = "ShangHai";
return Bar;
}
var ret = f();
ret(); // The printout is ?
BeiJing var city = "BeiJing";
function f(){
var city = "ShangHai";
function inner(){
console.log(city);
}
return inner;
}
var ret = f();
ret();
ShangHai

12. Custom object

# amount to python Dictionary type in 
The way 1: var d = {'name':'jason','age':18}
The way 2: var d = Object({'name':'jason','age':18})
When taking values, use points directly . that will do Pictured """
stay python in Use point method to realize dictionary value
class MyDict(dict):
def __getattr__(self, item):
return self.get(item)
def __setattr__(self, key, value):
self[key] = value res = MyDict(name='jason',age=18)
print(res.name)
print(res.age)
res.xxx = 123
print(res.xxx)
print(res)
"""

13. Built-in objects

# If you need to use built-in objects You need keywords new
stay python in
import date
date()
stay js in
new date() # establish Date object
// Method 1: Do not specify parameters
var d1 = new Date();
console.log(d1.toLocaleString()); // Method 2: The parameter is the date string
var d2 = new Date("2004/3/20 11:12");
console.log(d2.toLocaleString());
var d3 = new Date("04/03/20 11:12");
console.log(d3.toLocaleString()); // Method 3: The parameter is the number of milliseconds
var d3 = new Date(5000);
console.log(d3.toLocaleString());
console.log(d3.toUTCString()); // Method 4: The parameter is MM DD YY h min s Ms
var d4 = new Date(2004,2,20,11,12,0,300);
console.log(d4.toLocaleString()); // Milliseconds are not directly displayed # Date Object method :
var d = new Date();
//getDate() Acquisition date
//getDay () Get week
//getMonth () Get the month (0-11)
//getFullYear () Get the full year
//getYear () Year of acquisition
//getHours () For hours
//getMinutes () Get minutes
//getSeconds () Get seconds
//getMilliseconds () Get milliseconds
//getTime () Returns the cumulative number of milliseconds ( from 1970/1/1 The middle of the night ) # practice : Write code , Press the current date “2017-12-27 11:11 Wednesday ” Format output const WEEKMAP = {
0:" Sunday ",
1:" Monday ",
2:" Tuesday ",
3:" Wednesday ",
4:" Thursday ",
5:" Friday ",
6:" Saturday "
}; // Define the corresponding relationship between a number and a week function showTime() {
var d1 = new Date();
var year = d1.getFullYear();
var month = d1.getMonth() + 1; // Notice that the month starts from 0~11
var day = d1.getDate();
var hour = d1.getHours();
var minute = d1.getMinutes() < 10?"0"+d1.getMinutes():d1.getMinutes(); // The ternary operation var week = WEEKMAP[d1.getDay()]; // Week is from 0~6 var strTime = `
${year}-${month}-${day} ${hour}:${minute} ${week}
`;
console.log(strTime)
}; showTime(); ############################################################
# JSON object
serialize :
python in
import json
json.dumps() # serialize
json.loads() # Deserialization
js in
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
"""
############################################################ # RegExp object
# 1. There are two ways to define regular expressions
var reg1 = new RegExp("^[a-zA-Z][a-zA-Z0-9]{5,11}");
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/;
// Regular check data
reg1.test('jason666')
reg2.test('jason666')
true
# /* The first thing to note , Regular expressions cannot have spaces */ # 2. The global matching
The end of the regular expression does not add g It means that the matching is successful Add g Represents a global match
var s1 = 'egondsb dsb dsb';
s1.match(/s/)
s1.match(/s/g)
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/g
reg2.test('egondsb');
reg2.test('egondsb');
reg2.lastIndex;
# /* The second note , There is a... In global matching lastIndex attribute */ # 3. Parameters are not transmitted during verification It's equivalent to passing undefined
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/
reg2.test();
reg2.test(undefined); var reg3 = /undefined/;
reg3.test(); RegExp

14.BOM And DOM operation

# BOM(Browser Object Model) The browser object model , It makes JavaScript Ability to work with browsers “ dialogue ”>>>: Use js Operating the browser
# DOM (Document Object Model) The document object model , Through it , You can visit HTML All elements of the document >>>: Use js Operation front page 

15.BOM operation

# 1.window object All browsers support it window object . It means browser window 
window.innerHeight - The inside height of the browser window
window.innerWidth - The inside width of the browser window
window.open() - Open a new window
window.close() - Close the current window # 2.history object window.history Object contains the history of the browser
window.history.forward() - One page ahead
window.history.back() - One page back # 3.location object
window.location - Object to get the address of the current page (URL), And redirect the browser to a new page
window.location.href - Get the current page URL
window.location.href="URL" - Jump to the specified page
window.location.reload() - Reload page # 4. pop-up
Warning box : Warning boxes are often used to ensure that users can get some information
alert(" Did you see it? ?");
Confirmation box : The confirmation box is used to enable the user to verify or accept certain information
confirm(" Are you sure? ?")
Prompt box : The prompt box is often used to prompt the user to enter a value before entering the page
prompt(" Please enter "," Your answer ") # 5. Timing is related
By using JavaScript, We can execute the code after a certain time interval , Not immediately after the function is called - We call it timing events
setTimeout()
var t=setTimeout("JS sentence ", millisecond ) clearTimeout()
// Execute the corresponding function once after the specified time
var timer = setTimeout(function(){alert(123);}, 3000)
// Cancel setTimeout Set up
clearTimeout(timer); setInterval()
setInterval("JS sentence ", The time interval ) clearInterval()
clearInterval() Method can be cancelled by setInterval() Set up timeout
clearInterval() The parameters of the method must be set by setInterval() Back to ID value
// Execute the corresponding function every once in a while
var timer = setInterval(function(){console.log(123);}, 3000)
// Cancel setInterval Set up
clearInterval(timer);

Front end language js( contrast python Quick start ) More articles about

  1. Not a few frames , I'm sorry to say that I've done the front end : Vue.js - 60 Minute quick start

    Vue.js——60 Minute quick start   Vue.js It's a very hot one right now JavaScript MVVM library , It's built with the idea of data-driven and componentization . Compared with Angular.js,Vue.js Provides a more concise . It's easier to manage ...

  2. Python And C Basic language comparison (Python Quick start )

    The code is longer than the , It is recommended to use a computer to read this article . 10 Minute introduction Python What is used in this article is Python3 If you've ever learned C Language , Read this article , I believe you can quickly find the similarities and differences between the two languages , To get a quick start . Now we will introduce their similarities and differences ...

  3. Python A quick introduction to C Language similarities and differences

    The code is longer than the , It is recommended to use a computer to read this article . 10 Minute introduction Python What is used in this article is Python3 If you've ever learned C Language , Read this article , I believe you can quickly find the similarities and differences between the two languages , To get a quick start . Now we will introduce their similarities and differences . ...

  4. Python Quick start PDF Download the full HD version for free | Baidu cloud disk

    Baidu cloud disk :Python Quick start PDF Download the full HD version for free Extraction code :w5y8 Content abstract This is a book Python Quick start book , be based on Python 3.6 To write . This book is divided into 4 part , The first part explains Python Basic knowledge of , Yes ...

  5. Python Quick start

    Python Quick start One . Basic summary name :h.py Linux Command line run :python h.py notes . Numbers . character string : The basic types are only numbers and strings #python The comment goes like this ''' Of course, you can do the same ...

  6. Vue.js 60 Minute quick start

    Vue.js 60 Minute quick start Reprint author :keepfool link :http://www.cnblogs.com/keepfool/p/5619070.html Vue.js Introduce Vue.js This is the moment. ...

  7. Vue.js——60 Minute quick start ( turn )

    vue:Vue.js——60 Minute quick start <!doctype html> <html lang="en"> <head> <meta ch ...

  8. python Quick start and advanced

    python Quick start and advanced by cockroach

  9. 1、Python Quick start (0529)

    Learn the video from Margo education , Thank you, Margo programing language : user : Problem space Computer : solve the problem Solution space abstract : Machine code --> Microcode programming --> High-level language ( The higher and lower levels of language depend on whether the language is easy for human to understand or connect ...

  10. python Quick start —— Enter the basic knowledge you should have in data mining

    This article is to summarize python Important grammar in , Through this understanding, you can quickly understand a paragraph python The meaning of the code Python  Basic grammar to get you started  Python  Language . If you want to be right Python For a comprehensive understanding, please close ...

Random recommendation

  1. hdu 4622 Reincarnation

    http://acm.hdu.edu.cn/showproblem.php?pid=4622 Use the dictionary tree to map each string to an integer The same string corresponds to the same integer Put the integer corresponding to the string in an array ...

  2. ASP.NET MVC4 View layer _Razor operation Html Elements

    1 Commonly used Html label 1.1 Label Html grammar :<label for="UserName"> user name </label> Razor grammar :@Htm ...

  3. [AS/400] Basic concepts

    The content of this article comes from  Go4AS400 stay AS/400 in ,AS Represents the Application System.AS/400 It's a high security system , Users can only be restricted to . Dealing with specific information .AS/400 Integrated ...

  4. .Net How much do you know about asynchronous programming

    1. introduction Studying recently Abp frame , Find out Abp A lot of framework Api Both provide synchronous and asynchronous writing . Asynchronous programming says , You may say that asynchronous programming has good performance . But the good thing is , What kind of problems are introduced , And how to use it , I don't think I can answer it . since ...

  5. SqlExpress And LocalDB Link string conversion

    1. If it's a connection SQL Server Express databases, You need to define the connection string as :Data Source=.SQLEXPRESS" to "Data Source=( ...

  6. RTX Parameter configuration

        RTX The operating system is configured through the configuration file RTX_Conf_CM.c Realization .      stay MDK Open the file in the project RTX_Conf_CM.c, You can see the following figure 5.2 The project configuration wizard shown in :  20 Task C ...

  7. Linux practice : File cracking

    Linux practice : File cracking label ( The blank space to separate ): 20135321 Yu Jiayuan One . master NOP.JNE.JE.JMP.CMP Machine code for assembly instructions NOP:NOP The order is " Empty command ". Execute to NOP Instructions ...

  8. Linux Under the netfilter Cognition and routine operation

    Linux Under the netfilter Cognition and routine operation Preface Blog wrote today ,1 year 7 Months . But it includes all the writing experience , This timeline can reach three years . Last time I updated an article " Treasure of town station " , It is also the reading volume of this website ...

  9. CF757 C hash

    One number can become another , The number of various numbers in each group before and after the transformation is required to remain unchanged , Ask about the number of solutions For each number in each existing group, construct a sequence of situations that appear in each group , Such as 2 Appear in the first group and the second group once respectively, then add the label of the Group 1,2, Repeat times still need to add ...

  10. Linux Command application dictionary - The first 11 Chapter Shell Programming

    11.1 declare: Display or set Shell Variable 11.2 export: Display or set environment variables 11.3 set: Display and settings Shell Variable 11.4 unset: Delete variables or functions 11.5 env: see ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved