Table of contents
Introduction to JavaScript
What is JavaScript
- JavaScript is one of the most popular languages in the world and is a scripting language that runs on the client side (Script means script)
- Scripting language: No compilation is required. The js interpreter (js engine) interprets and executes line by line during operation. It is also called an interpreted language. It does not need to be compiled into machine code for execution. Like C++, it needs to be compiled. language is different
- Server-side programming is now also possible based on
Node.js
technology
The browser executes the JS process
The browser is divided into two parts: the rendering engine and the JS engine
Rendering engine : used to parse HTML
and CSS
, commonly known as the kernel, such as the blink of the chrome browser, the old version of webkit
JS engine : Also known as a JS interpreter. Used to read the JavaScript code in the webpage, process it and run it, such as the V8 of the chrome browser
The browser itself does not execute JS code, but executes JS code through a built-in JavaScript engine (interpreter). When the JS engine executes the code, it interprets each sentence of source code (converted into machine language) line by line, and then executes it by the computer. Therefore, the JavaScript language is classified as a scripting language and will be interpreted and executed line by line.
Composition of JS
The three major components of JavaScript are: ECMAScript
, DOM
,BOM
ECMAScript
ECMAScript is a programming language standardized by ECMA International (formerly the European Computer Manufacturers Association). This language is widely used on the World Wide Web. It is often called JavaScript or JScript, but the latter two are actually the implementation of the ECMAScript language. and extensions.
ECMAScript stipulates the programming syntax and basic core knowledge of JS, and is a set of JS syntax industry standards that all browser manufacturers abide by.
DOM
DOM is the abbreviation of Document Object Model (Document Object Model). It is a standard programming interface for processing Extensible Markup Language recommended by the W3C organization. Through the interface provided by DOM, various elements on the page can be operated (size, position, color, etc.).
BOM
BOM is the abbreviation of Browser Object Model. It provides a content-independent object structure that can interact with the browser window. The browser window can be operated through BOM, such as pop-up box, control browser jump, obtain resolution, etc.
How to import JS
1. Inline JS
<input type="button" value="" onclink="javascript:alert('你好')" />
- A single line or a small amount of JS code can be written in the event attribute of the HTML tag (the attribute starting with on), such as: onclink
- Pay attention to the use of single and double quotes: in HTML we recommend using double quotes, in JS we recommend using single quotes
- Poor readability, it is inconvenient to read when a large amount of JS code is compiled into HTML
- use in special circumstances
2. Embedded JS
<script>
alert('你好');
</script>
- You can write multiple lines of JS code to
3. External JS
<script src="my.js"></script>
- Conducive to the structuring of HTML page codes, separate JS codes from HTML pages, which is both beautiful and convenient
- Code cannot be written in the middle of script tags that refer to external JS files
- Suitable for situations where the amount of JS code is relatively large
Functions and Scope
The use of arguments
When we are not sure how many parameters to pass, it can be used arguments
to get. In JavaScript, arguments
it's actually a built-in object of the current function. All functions have a built-in arguments
object , and the arguments object stores all the actual parameters passed. What is stored is that the display form
arguments
of the passed actual parameter is a pseudo-array, so it can be traversed.
arguments
Pseudo-arrays have the following characteristics
- has a length attribute
- Store data by index
- Methods such as push and pop that do not have an array
<script>
// 当我们不确定有多少个参数传递的时候,可以用 arguments 来获取。
//在 JavaScript 中,arguments 实际上它是当前函数的一个内置对象。
//所有函数都内置了一个 arguments 对象,arguments 对象中存储了传递的所有实参。
// 函数声明
function fn() {
console.log(arguments); //里面存储了所有传递过来的实参
console.log(arguments.length); // 3
console.log(arguments[2]); // 3
}
// 函数调用
fn(1,2,3);
// 利用函数求任意个数的最大值
function maxValue() {
var max = arguments[0];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
console.log(maxValue(1,2,3,4));;
</script>
Global Variables vs Local Variables
global variable
- Variables declared in the global scope are called global variables (variables defined outside the function)
- Global variables can be used anywhere in the code
- Variables declared with var in the global scope are global variables
- In special cases, variables declared without var in the function are also global variables (not recommended)
local variable
- Variables declared under the local scope are called local variables (variables defined inside the function)
- Local variables can only be used inside the function
- Variables declared with var inside a function are local variables
- Function parameters are actually local variables
Differences
Global variables: can be used anywhere, and will only be destroyed when the browser is closed, so it takes up more memory.
Local variables: only used inside the function, and will be initialized when the code block where it is located is executed; When the code block is finished running, it will be destroyed, so it saves memory space
<script>
// 现阶段没有块级作用域{},只有全局和局部,es6才新增块级
// 在C++不行
// if(3 < 5) {
// int num = 10;
// }
// cout<<num;
if(3 < 5) {
var num = 10;
}
console.log(num);
// 报错,局部变量只能在里面使用
function sort() {
var num2 = 22;
}
console.log(num2);
</script>
pre-parsing
JavaScript code is executed by the JavaScript parser in the browser. The JavaScript parser is divided into two steps when running JavaScript code: pre-parsing and code execution.
Pre-parsing: the js engine will promote all var and function in js to the front of the current scope
Code execution: execute JS statements from top to bottom
Preparsing will only happen for variables and functions defined via var. Learning pre-parsing can let us know why the value of the variable is accessed before the variable declaration undefined
, and why the function can be called before the function declaration.
<script>
// js引擎会把js里面所有的 var 还有 function 提升到当前作用域的最前面
// 1.undefined
console.log(num1);
var num1 = 11;
// var num1;
// console.log(num1);
// num1 = 11;
// 2.22
fun1();
function fun1() {
console.log(22);
}
// 函数声明
// fun1();
// function函数提升到当前作用域(全局)最前面声明
// function fun1() {
// console.log(22);
// }
// 3.报错
fun2();
var fun2 = function() {
console.log(33);
}
// var fun2;
// fun2();函数未声明就调用,报错
// fun2 = function() {
// console.log(33);
// }
</script>
object
Three ways to create objects
1. Use literals to create objects
Object literal: it is the curly braces { } that contains the properties and methods that express this specific thing (object)
{ }, which is expressed in the form of key-value pairs
Key: equivalent to the attribute name
Value: equivalent to the attribute value, which can be of any type The value of (numeric type, string type, Boolean type, function type, etc.)
// 1.{}字面量
var obj = {
name: 'hai',
sex: '男',
fun: function() {
alert('大家好');
}
}
// 调用对象的方式
console.log(obj.name);
console.log(obj['name']);
obj.fun();
2. Use new Object to create objects
var ObjectName = new Object();
var obj2 = new Object();
obj2.name = 'hhh';
obj2.fun2 = function() {
alert('你好');
}
console.log(obj2.name);
console.log(obj2['name']);
obj2.fun2();
3. Create objects using constructors
Constructor: It is a special function, which is mainly used to initialize the object, that is, to assign the initial value to the object member variable, and it is always used together with the new operator. We can extract some public properties and methods in the object, and then encapsulate them into this function.
When using constructors, pay attention to the following two points:
- The constructor is used to create a certain type of object, and its first letter should be capitalized
- Constructors only make sense when used with new
function Star(uname ) {//大写
this.name = uname;
this.fun3 = function(sang) {
console.log(sang);
}
}
new Star();//空对象
var jjl = new Star('周杰伦');
console.log(typeof jjl);//typeof 运算符返回数据类型
console.log(jjl.name);
jjl.fun3('稻香');
iterate over object properties
for(var k in jjl) {
console.log(k);//返回属性
console.log(jjl[k]);//返回属性值
}
Summary of variables, properties, functions, methods
Variable: separate declaration and assignment, exists independently
Attribute: the variable in the object is called attribute, does not need to be declared, and is used to describe the characteristics of the object
function: exists alone, and the method can be called by "function name ()"
: object The function inside is called a method, and the method does not need to be declared. It can be called by using the method of "object. method name ()". The method is used to describe the behavior and function of the object.
new keyword execution process
new does four things when executed:
- Create a new empty object in memory.
var jjl = new Star('周杰伦');
- Let this point to this new object.
this.name = uname;
- Execute the code in the constructor and add properties and methods to the new object
- Return this new object (so there is no need to return in the constructor)
built-in object
Objects in JavaScript are divided into three types: custom objects, built-in objects, and browser objects.
Built-in objects refer to some objects that come with the JS language. JavaScript
provides several built-in objects: Math, Date, Array, String, etc.
Math object
Math is a built-in object that has some properties of mathematical constants and methods of mathematical functions. Math is not a function object. Unlike other global objects, Math is not a constructor. All properties and methods of Math are static.
<script>
console.log(Math.max(1,2,3));
// 封装自己的数学对象
var myMath = {
max: function () {
var max = arguments[0];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
}
console.log(myMath.max(1,2,3,4));
console.log('\n');
// 取整
console.log(Math.floor(1.2));//向下取整1
console.log(Math.floor(1.6));//1
console.log(Math.ceil(1.2));//向上取整2
console.log(Math.ceil(1.6));//2
// 四舍五入
console.log(Math.round(1.2));//1
console.log(Math.round(1.6));//2
console.log(Math.round(-1.2));//-1
console.log(Math.round(-1.5));//-1特殊,.5往大的取
console.log('\n');
// 随机数函数 随机返回一个小数,其取值范围是 [0,1),左闭右开 0 <= x < 1(表示一种概率)
console.log(Math.random());
console.log('\n');
// 得到两个数之间的随机整数,并且包含这两个整数(因为左闭右开所以要+1)
function myRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(myRandom(1, 10));;
</script>
Date object
Creates a JavaScript Date instance that represents a moment in time. Date objects are based on the Unix Time Stamp, which is the number of milliseconds since January 1, 1970 (UTC).
- The Date object is different from the Math object, it is a constructor, so we need to instantiate it before using it
- The only way to create a new Date object is through the new operator
- Date instance for working with dates and times
method name | illustrate | the code |
---|---|---|
getFullYear() | Get current year | dObj.getFullYear() |
getMonth() | Get the current month (0-11) | dObj.getMonth() |
getDate() | Get today's date | dObj.getDate() |
getDay() | Get the day of the week (Sunday 0 to Saturday 6) | dObj.getDay() |
getHours() | get current hour | dObj.getHours() |
getMinutes() | get current hour | dObj.getMinutes() |
getSeconds() | get the current second | dObj.gerSeconds() |
<script>
// 日期对象Date() 是一个构造函数 必须使用new来调用我们创建的对象
var arr = new Array();
// 如果没有输入任何参数,则 Date 的构造器会依据系统设置的当前时间来创建一个 Date 对象。
var date = new Date();
console.log(date);
// 参数常用写法1.数字 2.字符串
// console.log(Date('2022-10-1 20:55:10'));没new实例化,不能实现
var date1 = new Date('2022-10-1 20:55:10');
console.log(date1);
console.log('\n');
var date2 = new Date();
console.log(date2.getFullYear());
console.log(date2.getMonth() + 1);//0~11月
console.log(date2.getDate());
console.log(date2.getDay());//1~6~0星期天是0
// 封装一个函数返回当前的时分秒 格式 08:08:08
function getTimer() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s;
}
console.log(getTimer());
</script>
Get the total milliseconds of the time
<script>
// 获取Date总的毫秒数 不是当前时间的毫秒数 而是距离1970年1月1号过了多少毫秒数
// 实例化Date对象
var date = new Date();
// 1 .通过 valueOf() getTime() 用于获取对象的原始值
console.log(date.valueOf()); //得到现在时间距离1970.1.1总的毫秒数
console.log(date.getTime());
// 2.简单的写法
var date1 = +new Date(); // +new Date()返回的就是总的毫秒数,
console.log(date1);
// 3. HTML5中提供的方法 获得总的毫秒数 有兼容性问题
console.log(Date.now());
</script>
Countdown case
<script>
function getTimer(time) {
var end = +new Date(time);
var now = +new Date();
var countDown = end - now;
countDown /= 1000;
var d = parseInt(countDown / 60 /60 / 24);
var h = parseInt(countDown / 60 /60 % 24);//取余24进位
var m = parseInt(countDown / 60 % 60);
var s = parseInt(countDown % 60);//取余60进位
return d + '天' + h + '时' + m + '分' + s + '秒';
}
console.log(getTimer('2022-10-11 22:43:20'));;
</script>
Array object
Two ways to create an Array array object
- Literal way
- new Array()
Determine whether it is an array
Two methods:
instanceof
operator, which can determine whether an object belongs to a certain typeArray.isArray()
Used to determine whether an object is an array, isArray() is a method provided in HTML5
<script>
var arr = [];
var obj = {
};
// 1.instanceof 运算符 检测是否为数组,可以翻译为“是”
console.log(arr instanceof Array);
console.log(obj instanceof Array);
// 2.Array.isArray(参数);h5新增方法 IE9以上版本支持
console.log(Array.isArray(arr));
console.log(Array.isArray(obj));
</script>
array sort
method name | illustrate | Whether to modify the original array |
---|---|---|
reverse() | Reverses the order of elements in an array, no arguments | This method changes the original array and returns a new array |
sort() | Sort the elements of an array | This method changes the original array and returns a new array |
<script>
var arr = [3,22,4,1];
arr.sort()
console.log(arr);//默认排序顺序是在将元素转换为字符串,22不生效
// 解决 内联函数 要比较数字而非字符串,比较函数可以简单的用 a 减 b,如下的函数将会将数组升序排列 反之
arr.sort(function(a, b) {
return a - b;
});
console.log(arr);
</script>
array index
method name | illustrate | return value |
---|---|---|
indexOf() | Finds the first index of a given element in an array | Returns the index number if it exists, or -1 if it does not |
lastIndexOf() | At the last index in the array, indexing from the back to the front | Returns the index number if it exists, or -1 if it does not |
Case array deduplication
The core algorithm for removing duplicate elements in the array [1,2,3,3,4,4]
: we traverse the old array, and then take the old array elements to query the new array, if the element does not appear in the new array, we Just add it, otherwise don't add it.
<script>
function unique(arr) {
var newArray = [];
for (var i = 0; i < arr.length; i++) {
if (newArray.indexOf(arr[i])== -1) {
//新数组不存在就加入
newArray.push(arr[i]);
}
}
return newArray;
}
var demo = unique([1,2,3,3,4,4]);
console.log(demo);
</script>
String object
basic packaging type
In order to facilitate the operation of basic data types, JavaScript also provides three special reference types: String, Number and Boolean.
The basic wrapper type is to wrap simple data types into complex data types, so that the basic data types have attributes and methods. For example, a string can call the length method to find its length.
Wrap basic data types into complex data types, the execution process is as follows:
// 1.生成临时变量,把简单类型包装为复杂数据类型
var temp = new String('andy');
// 2.赋值给我们声明的字符变量
str = temp;
// 3.销毁临时变量
temp = null;
immutable string
The value in the string is immutable. Although it seems that the content can be changed, the essence is that the address has changed, and a new memory space has been opened in the memory.
var str = 'abc';
str = 'hello';
// 当重新给 str 赋值的时候,常量'abc'不会被修改,依然在内存中
// 重新给字符串赋值,会重新在内存中开辟空间,这个特点就是字符串的不可变
var str = '';
for(var i = 0; i < 1000000; i++){
str += i;
}
console.log(str);
// 运行出结果需要花费大量时间,因为需要不断的开辟新的空间
return position by character
All string methods will not modify the string itself (string is immutable), and a new string will be returned after the operation is completed.
method name | illustrate |
---|---|
indexOf('The character to find', the starting position) | Returns the position of the specified content in the meta string, or -1 if it cannot be found, and the starting position is the index number |
lastIndexOf() | Search from back to front, only find the first match |
Find the case of repeated strings
Find the positions and times of all o occurrences in the string "aoooaaoo"
Core algorithm: find the first o first, as long as str.indexOf('o')
it is not -1 (that is, there is still), continue to look back
<script>
var str = "aoooaaoo";
var index = str.indexOf('o');
var num = 0;
while (index != -1) {
console.log(index);
num++;
index = str.indexOf('o', index + 1);
}
console.log(num);
</script>
return character by position
method name | illustrate | use |
---|---|---|
charAt(index) | Returns the character at the specified position (the index number of the index string) | str.charAt(0) |
charCodeAt(index) | Get the ASCII code of the character at the specified position (index index number) | str.charCodeAt(0) |
str[index] | Get the character at the specified position | HTML, IE8+ support and charAt() equivalent |
Determine the character that appears most frequently in a string "aeieeouuee", and count the number of times.
Core algorithm: use charAt(index)
the traversal string, store the characters in the object, and finally traverse the object
<script>
// 有一个对象 来判断是否有该属性 对象['属性名']
var obj = {
sex: '男'
};
if (obj['sex']) {
console.log(true);
} else {
console.log(false);
}
// 判断一个字符串 'aeieeouuee' 中出现次数最多的字符,并统计其次数。
// 利用charAt(index)遍历字符串,字符储存给对象,最后遍历对象
var str = "aeieeouuee";
var o = {
};
for (var i = 0; i < str.length; i++) {
var chars = str.charAt(i);
if (o[chars]) {
//如果字符存在,属性值加加
o[chars]++;
} else {
o[chars] = 1;
}
}
console.log(o);
// 遍历对象
var max = 0;
var ch = '';
for (var k in o) {
if (o[k] > max) {
max = o[k];
ch = k;
}
}
console.log(max);
console.log('最多的字符是' + ch);
</script>
String manipulation methods
method name | Method name description |
---|---|
concat(str1,str2,str3…) | Used to concatenate two or pairs of strings. concatenate string |
substr(start,length) | Starting from the start position (index number), the number of length to take. |
slice(start,end) | Start from the start position, intercept to the end position, and the end cannot be obtained (both are index numbers) |
substring(start,end) | Start from the start position, intercept to the end position, and the end cannot be obtained (basically the same as slice, but negative values are not accepted) |
replace (character to be replaced, string to be replaced) | Replace some characters with other characters in a string |
split('separator') | split string into array |
<script>
// 连接与截取
var str = '1234';
console.log(str.concat('456')); //1234456
console.log(str.substr(2, 2)); //34
// 替换
console.log(str.replace('1', '0')); //0234
// 替换所有e
var str2 = 'aeeeiou';
while (str2.indexOf('e') != -1) {
//只要存在就替换
str2 = str2.replace('e', 'E');
}
console.log(str2); //aEEEiou
// 切分字符串为数组 对比 join把数组转换为字符串
var str3 = '1,2,3,4';
console.log(str3.split(',')); //['1', '2', '3', '4']
</script>
Simple and complex types
Simple types are also called basic data types or value types , and complex types are also called reference types .
Basic data type : the value itself is stored in the variable during storage, such as:
string, number, boolean, undefined, null
Reference type : complex data type, only the address (reference) is stored in the variable during storage, such as:
through new Objects created by keywords (system objects, custom objects), such as Object, Array, Date, etc.
different memory allocation
Simple type
The data of the variable is directly stored in the variable (that is, in the stack space). The
reference type
stores the address in the stack space, and the real object instance is stored in the heap space, and the address of the stack points to the object in the heap area
The difference between different types of parameter passing
Knowing the memory allocation of different data, the variables passed by parameters are also different. Simple type parameter passing copies a value to a formal parameter, so any modification of the formal parameter inside the method will not affect the external variable.
When a reference type variable is passed to a formal parameter, the heap address saved in the stack space of the variable is actually copied to the formal parameter. The formal parameter and the actual parameter actually store the same heap address, so the operation is the same object. .