当前位置:网站首页>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 .

边栏推荐
- Calculate the maximum path sum of binary tree
- 3 A VTT端接 稳压器 NCP51200MNTXG资料
- js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
- Bom Dom
- 应用LNK306GN-TL 转换器、非隔离电源
- Hash table acwing 841 String hash
- Heap acwing 839 Simulated reactor
- C#运算符
- What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
- Fluent fluent library encapsulation
猜你喜欢

移动式布局(流式布局)

Openssh remote enumeration username vulnerability (cve-2018-15473)

防抖 节流

Heap acwing 839 Simulated reactor

Hash table acwing 841 String hash

Linear DP acwing 895 Longest ascending subsequence

js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)

bellman-ford AcWing 853. Shortest path with side limit

上手报告|今天聊聊腾讯目前在用的微服务架构
![[FFH] little bear driver calling process (take calling LED light driver as an example)](/img/e7/153ae9f1befc12825d277620049f9d.jpg)
[FFH] little bear driver calling process (take calling LED light driver as an example)
随机推荐
架构师必须了解的 5 种最佳软件架构模式
百款拿来就能用的网页特效,不来看看吗?
Mongodb redis differences
In development, why do you find someone who is paid more than you but doesn't write any code?
About the loading of layer web spring layer components, the position of the layer is centered
Browser node event loop
js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)
Window10 upgrade encountered a big hole error code: 0xc000000e perfect solution
JDBC prevent SQL injection problems and solutions [preparedstatement]
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
通过反射执行任意类的任意方法
Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
Input box assembly of the shutter package
China traffic sign detection data set
. Net, C # basic knowledge
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
Use sqoop to export ads layer data to MySQL
Anti shake throttle
Linear DP acwing 898 Number triangle
JSON序列化 与 解析