当前位置:网站首页>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
var
You can start with Used in declarations ( unreasonable ), uselet
When a keyword declares a variable , must Declaration before usevar
Declared variables can Repeat statement ( unreasonable ) ,let It is not allowed to declare a variable more than once .var
Variable Promotion ,let
Declared 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 .
var
yes 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 becomewindow
Object 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
- 浏览器存储方案
- 线性DP AcWing 895. 最长上升子序列
- [ybtoj advanced training guidance] cross the river [BFS]
- [ybtoj advanced training guidance] judgment overflow [error]
- Drools dynamically add, modify, and delete rules
- China traffic sign detection data set
- Leetcode - Sword finger offer 51 Reverse pairs in an array
- In development, why do you find someone who is paid more than you but doesn't write any code?
猜你喜欢
区间DP AcWing 282. 石子合并
Why do programmers have the idea that code can run without moving? Is it poisonous? Or what?
In development, why do you find someone who is paid more than you but doesn't write any code?
Rust search server, rust quick service finding tutorial
包管理工具
Enhance network security of kubernetes with cilium
染色法判定二分图 AcWing 860. 染色法判定二分图
C#运算符
Redis bloom filter
js1day(输入输出语法,数据类型,数据类型转换,var和let区别)
随机推荐
2.6 using recursion and stack - [tower of Hanoi problem]
js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
Interview questions for software testing - a collection of interview questions for large factories in 2022
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
Deep Copy Event bus
Modular commonjs es module
Redis transaction mechanism implementation process and principle, and use transaction mechanism to prevent inventory oversold
Linear DP acwing 896 Longest ascending subsequence II
Some sudden program ideas (modular processing)
Drools executes string rules or executes a rule file
Docker compose configuration mysql, redis, mongodb
CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
Intel internal instructions - AVX and avx2 learning notes
Counting class DP acwing 900 Integer partition
Do you know all the interface test interview questions?
ArrayList与LinkedList效率的对比
High performance erasure code coding
Rust search server, rust quick service finding tutorial