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

边栏推荐
- 包管理工具
- Efficiency comparison between ArrayList and LinkedList
- bellman-ford AcWing 853. 有边数限制的最短路
- AI mid stage technology research
- C#运算符
- The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
- C#修饰符
- How to write a pleasing English mathematical paper
- js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)
- 哈希表 AcWing 840. 模拟散列表
猜你喜欢

The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night

Heap acwing 838 Heap sort

传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE

移动式布局(流式布局)

This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry

Package management tools

BOM DOM

Simple understanding of ThreadLocal

spfa AcWing 852. spfa判断负环

Browser node event loop
随机推荐
This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry
深拷贝 事件总线
"As a junior college student, I found out how difficult it is to counter attack after graduation."
染色法判定二分图 AcWing 860. 染色法判定二分图
浏览器node事件循环
Linear DP acwing 898 Number triangle
8 examples of using date commands
2.6 using recursion and stack - [tower of Hanoi problem]
[ybtoj advanced training guidance] cross the river [BFS]
获取文件版权信息
架构师必须了解的 5 种最佳软件架构模式
线性DP AcWing 897. 最长公共子序列
bellman-ford AcWing 853. 有边数限制的最短路
一些突然迸发出的程序思想(模块化处理)
1380. Lucky numbers in the matrix [two-dimensional array, matrix]
There is a hidden danger in CDH: the exchange memory used by the process of this role is XX megabytes. Warning threshold: 200 bytes
哈希表 AcWing 840. 模拟散列表
C#修饰符
Do you know all the interface test interview questions?
spfa AcWing 851. SPFA finding the shortest path