当前位置:网站首页>Js1day (input / output syntax, data type, data type conversion, VaR and let differences)
Js1day (input / output syntax, data type, data type conversion, VaR and let differences)
2022-07-02 12:44:00 【By the Difeng River】
List of articles
- Input output syntax :
- Template string ( Concatenate strings and variables )
- Writing position :
- var and let difference ( Do not apply var,const first ,let secondly ):
- const Statement :
- data type
- Get the data type of the test variable (typeof)
- Data type conversion
- Interpreted and compiled languages
- User order information case
Input output syntax :
- Input :
prompt() - Output :
alert()document.write()console.log()
Template string ( Concatenate strings and variables )
Symbol :
``
Press... On the keyboard in English input mode tab The key above the key (1 The key on the left )
Content splicing variable , use ${} Wrap variable
Example :
let age = "18"
let love = ` Fall in love `
let name = `${
age} Not often `
document.write(`<span>${
name} Talk quickly ${
love}</span>`) //18 Not often in love
Writing position :
- inline JavaScript( Write it in the tag statement )
- Inside JavaScript – writes Above the label
- external JavaScript - adopt src introduce html On the page , however
<script>Don't write on the label , Otherwise it will be ignored
<body>
<button onclick="alert(' I'm your verification code ')"> Am I </button>
<script> document.write(" What am I ") document.write("<h1>document Can read html label </h1>") </script>
</body>
var and let difference ( Do not apply var,const first ,let secondly ):
let In order to solve var Some of the problems
varYou can start with Used in declarations ( unreasonable ), useletWhen a keyword declares a variable , must Declaration before usevarDeclared variables can Repeat statement ( unreasonable ) ,let It is not allowed to declare a variable more than once .varVariable Promotion ,letDeclared variables are not promoted in the scope
Use var when , The following code will not report an error . This is because variables declared with this keyword will be automatically promoted to the function scope
Top :
function foo() {
console.log(age);
var age = 26;
}
foo(); // undefined
The reason why you won't report an error , Because ECMAScript The runtime sees it as equivalent to the following code :
function foo() {
var age;
console.log(age);
age = 26;
}
foo(); // undefined
That's what's called “ promote ”(hoist), That is to say Drag all variable declarations to the top of the function scope .
varyes Function scope ,let yes Block scope
The key question is , Use var The variable defined by the operator becomes a local variable of the function that contains it . such as , Use var
Define a variable inside a function , This means that the variable will be destroyed when the function exits
function test() {
var message = "hi"; // local variable
}
test();
console.log(message); // error !
Remove the previous var After the operator ,message It becomes a global variable .( Not recommended )
function test() {
message = "hi"; // Global variables
}
test();
console.log(message); // "hi"
let Follow var It's about the same , But there are very important differences . The most obvious difference is ,let The scope of the declaration is Block scope ,
and var The scope of the declaration is Function scope .
if (true) {
var name = 'Matt';
console.log(name); // Matt
}
console.log(name); // Matt
if (true) {
let age = 26;
console.log(age); // 26
}
console.log(age); // ReferenceError: age No definition
ad locum ,age The reason why variables cannot be in if The block is referenced outside , Because of its scope Only inside this block (‘{}’ Inside is a piece ). Block scope
Is a subset of the scope of a function , So it applies to var The same scope restrictions apply to let.
- Global declarations
And var Different keywords , Use let Variables declared in the global scope do not becomewindowObject properties (var Declared variables will )
var name = 'Matt';
console.log(window.name); // 'Matt'
let age = 26;
console.log(window.age); // undefined
however ,let The declaration still occurs in the global scope , The corresponding variables will be stored in the life cycle of the page . therefore , for fear of SyntaxError, You must ensure that the page does not declare the same variable repeatedly .
const Statement :
const The behavior and let Basically the same , The only important difference is that when you declare a variable with it, you must initialize the variable at the same time , And
Try to modify const Declared variables can cause runtime errors .
// const The scope of the declaration is also a block
const name = 'Matt';
if (true) {
const name = 'Nicholas';
}
console.log(name); // Matt
data type
js The data type of is Only the program is running , Determined by the value to the right of the equal sign .
- JS Is a weak data type , What kind of variable does it belong to , Only after assignment , We can confirm
- Java It's a strong data type for example int a = 3 It has to be an integer
js Two types of data types :
- Simple data type :
Number,String,Boolean,Undefined,Null - Complex data type :
object
Digital (Number)
Base number


Three special values


isNaN()
Used to determine whether a variable is a non numeric type , return true perhaps false
var usrAge=21;
var isOk=isNaN(userAge);
console.log(isNum); //false, 21 It's not a non number
var usrName="andy";
console.log(isNaN(userName)); //true,"andy" It's a non number
String type (String)
String type can be any text in quotation marks , Its grammar is Double quotes “” and Single quotation marks ’'( Single quotation marks are more recommended )
String escape character

String quotes nested
JS It can be used Single quotes nested double quotes , Or use Double quotes nested single quotes ( Double outside and single inside , Single outside and double inside )
But you can't nest the same kind of quotation marks !!
var strMsg = ' I am a " Gao Shuai Fu " Program the ape '; // It can be used '' contain ""
var strMsg2 = " I am a ' Gao Shuai Fu ' Program the ape "; // It can also be used. "" contain ''
// Common mistakes
var badQuotes = 'What on earth?"; // Report errors , You can't Single and double quotation marks
String length (length)
Through strings length Property to get the length of the entire string .( Note that spaces count as one character )
var strMsg = " What is this? ";
alert(strMsg.length); // Show 3
String splicing
character string + Any kind of = The new string after splicing
//1.1 character string " Add up "
alert('hello' + ' ' + 'world'); // hello world
//1.2 Numeric strings " Add up "
alert('100' + '100'); // 100100
//1.3 Numeric strings + The number
alert('11' + 12); // 1112
Undefined and Null
A variable that is not assigned after declaration has a default value undefined ( If you join or add , Pay attention to the results )
var variable;
console.log(variable); // undefined
console.log(' Hello ' + variable); // Hello undefined
console.log(11 + variable); // NaN
console.log(true + variable); // NaN
A declaration variable is given to null value , The value stored in it is empty (null It's a object type )
var vari = null;
console.log(' Hello ' + vari); // Hello null
console.log(11 + vari); // 11
console.log(true + vari); // 1
Get the data type of the test variable (typeof)
typeof Can be used to get the data type of the test variable
var num = 18;
console.log(typeof num) // result number
Data type conversion
Convert to string

Convert to digital ( a key )

console.log(parseInt("120px")); //120 Removed px Company
console.log(parseInt("rem120px")); //NaN
console.log('12' - 10); //2
Be careful parseInt and parseFloat The case of words , this 2 The point is
Implicit conversion is when we do arithmetic operations ,JS Automatically converted the data type
Convert to Boolean

- Representational space 、 Negative values are converted to
false, Such as ‘’、0、NaN、null、undefined - The rest of the values are converted to
true
Interpreted and compiled languages


User order information case
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Under the bridge opening of Hong Kong Zhuhai Macao Bridge </title>
<style> * {
margin: 0; padding: 0; } table {
margin: 0 auto; text-align: center; border-collapse: collapse; } table th, td {
border: 1px solid #000; padding: 15px; } table caption {
margin: 15px 0; } </style>
</head>
<body>
<script> let price = prompt("price:") //1999 let num = prompt("num:") //3 let address = prompt("address:") // Under the bridge opening of Hong Kong Zhuhai Macao Bridge let total = price * num document.write(` <table> <caption> <h2> Order payment confirmation interface </h2> </caption> <tr> <th> Name of commodity </th> <th> commodity price </th> <th> The number </th> <th> The total price </th> <th> Shipping address </th> </tr> <tr> <td> Huawei mate40pro</td> <td class="price">${
price} element </td> <td class="num">${
num}</td> <td class="total">${
total} element </td> <td class="address">${
address}</td> </tr> </table>`) </script>
</body>
</html>
Notice the cells here Border merge , border-collapse: collapse; ( The border collapses ) Obviously, it's not using the code learned before .

边栏推荐
- IPhone 6 plus is listed in Apple's "retro products" list
- Linear DP acwing 902 Shortest editing distance
- Direct control PTZ PTZ PTZ PTZ camera debugging (c)
- spfa AcWing 852. spfa判断负环
- Openssh remote enumeration username vulnerability (cve-2018-15473)
- . Net, C # basic knowledge
- Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
- Oracle从入门到精通(第4版)
- 浏览器存储方案
- Drools terminates the execution of other rules after executing one rule
猜你喜欢

bellman-ford AcWing 853. 有边数限制的最短路

The coloring method determines the bipartite graph acwing 860 Chromatic judgement bipartite graph
![[ybtoj advanced training guide] similar string [string] [simulation]](/img/eb/acfefc7f85018fe9365d13502e2b0a.jpg)
[ybtoj advanced training guide] similar string [string] [simulation]

spfa AcWing 852. spfa判断负环

High performance erasure code coding

Deep copy event bus

Efficiency comparison between ArrayList and LinkedList

JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)

Js6day (search, add and delete DOM nodes. Instantiation time, timestamp, timestamp cases, redrawing and reflow)

Embedded Software Engineer career planning
随机推荐
Drools terminates the execution of other rules after executing one rule
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
堆 AcWing 838. 堆排序
Rust语言文档精简版(上)——cargo、输出、基础语法、数据类型、所有权、结构体、枚举和模式匹配
深拷貝 事件總線
spfa AcWing 852. spfa判断负环
Bom Dom
CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
Floyd AcWing 854. Floyd finds the shortest path
模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计
Why do programmers have the idea that code can run without moving? Is it poisonous? Or what?
. Net, C # basic knowledge
Calculate the maximum path sum of binary tree
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
Fluent fluent library encapsulation
Js8day (rolling event (scroll family), offset family, client family, carousel map case (to be done))
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
正确遍历EntryList方法
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
There is a hidden danger in CDH: the exchange memory used by the process of this role is XX megabytes. Warning threshold: 200 bytes