JavaScript
Overview of JavaScript
JavaScript, or JS for short, is a scripting language that runs mainly in browsers. It can read and modify page content, respond to user actions, send network requests, and achieve dynamic interactive effects.
Modern JavaScript can also run on servers or other operating environments, but this chapter focuses on JavaScript in browsers.
Differences between JavaScript and Java
JavaScript and Java have similar names, but they are two different programming languages.
| comparison item | Java | JavaScript |
|---|---|---|
| type system | Static types, variable types are usually determined at compile time | Dynamically typed, variables can hold different types of values |
| Common operating methods | Compiled to bytecode and executed by the JVM | Parsed, compiled and executed by the JavaScript engine |
| mainly used | Back-end, desktop, Android, etc. | Web page interaction, front-end development, service-side development, etc. |
| object-oriented manner | class-based | Based on the prototype mechanism, it also supports class syntax |
Java was originally developed by Sun and later maintained by Oracle;JavaScript was originally developed by Netscape.
Composition of JavaScript
JavaScript development in a browser usually involves the following parts:
-
ECMAScript: Specify the core syntax, types, operators, objects, statements, etc. of JavaScript.
-
DOM: Document Object Model, used to manipulate HTML documents.
-
BOM: Browser Object Model, a browser object model, used to operate browser windows, addresses, history, timers, etc.
-
event: The browser triggers events when clicks, inputs, loads and other operations occur, and JavaScript can register processing functions.
How to use JavaScript
internal script
A small amount of JavaScript can be written on the <script> In the label:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>内部脚本</title>
<script>
console.log("页面脚本开始执行");
</script>
</head>
<body>
页面内容
</body>
</html>external script
When there is a lot of code, it should be saved as a separate .js Document, then pass src Attribute introduction:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>外部脚本</title>
<script src="js文件地址"></script>
</head>
<body>
页面内容
</body>
</html>with src attributes <script> The label still needs to end the label.
Variables and data types
JavaScript has data types, but the variables themselves do not need to declare fixed types. When the value held by a variable changes, its type may also change. This is called dynamic typing.
common data types
Common types at this stage are as follows:
-
string: String. -
number: Numbers, including integers and decimals. -
boolean: Boolean value, that istrueandfalse。 -
undefined: Variable is declared but not yet assigned. -
null: Represents a null value that is actively set.
In addition, JavaScript also provides object types, and bigint、symbol and other types.
define variables
Old versions of code are often used var:
var name = "张三";
var age = 20;
var sex = "男";
alert("姓名:" + name + ",年龄:" + age + ",性别:" + sex);
console.log("name 的类型:" + typeof name);
console.log("age 的类型:" + typeof age);
console.log("sex 的类型:" + typeof sex);Modern JavaScript usually takes precedence let and const:
const name = "张三";
let age = 20;
age = 21;-
const: Variable bindings cannot be reassigned. -
let: Variables can be reassigned and have block-level scope.
process control
branch statements
Common branch statements in JavaScript include if、if...else and switch。
const score = 85;
if (score >= 60) {
console.log("及格");
} else {
console.log("不及格");
}loop statement
Common cycles include for、while and do...while。
for (let i = 0; i < 5; i++) {
console.log(i);
}Operators and type conversions
equality comparison
JavaScript provides == and ===:
const value1 = "10";
const value2 = 10;
console.log(value1 == value2); // true
console.log(value1 === value2); // false-
==: Implicit type conversions may occur before comparison. -
===: No implicit type conversion is performed and both type and value are required to be equal.
Practical development usually takes precedence === and !==, reduce the ambiguity caused by implicit conversions.
numerical operation
In Java, integer division is performed when dividing two integers, while ordinary numerical values in JavaScript are used uniformly. number Type:
const value = 123;
console.log((value / 1000) * 1000); // 123JavaScript’s number Using floating point numbers, so although this example obtains 123, but floating point precision errors may still occur in some decimal operations. for example 0.1 + 0.2 is not strictly equal to 0.3。
string operations
+ String splicing is usually performed when string operands are present:
console.log("123" + "23"); // "12323"- String splicing is not supported. JavaScript will try to convert strings to numbers:
const value1 = "123";
const value2 = "23";
console.log(value1 - value2); // 100When the conversion cannot be made to a significant number, the result is usually NaN。
Boolean transformation
In conditional judgment, JavaScript converts the value to a Boolean value.0, empty string,null、undefined and NaN Equivalent values are treated as false values, and most other values are treated as true values.
const value1 = true;
const value2 = false;
console.log(value1 == 1); // true,发生了类型转换
console.log(value1 === 1); // false,类型不同
console.log(value2 == 0); // true,发生了类型转换Use DOM to output content
can use document Object manipulation page. The following example dynamically generates a nine-nine multiplication table:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>九九乘法表</title>
</head>
<body>
<div id="tableBox"></div>
<script>
let html = "<table border='1'>";
for (let i = 1; i <= 9; i++) {
html += "<tr>";
for (let j = 1; j <= i; j++) {
html += "<td>" + j + "×" + i + "=" + i * j + "</td>";
}
html += "</tr>";
}
html += "</table>";
document.getElementById("tableBox").innerHTML = html;
</script>
</body>
</html>document.write() You can also write content to the document, but calling it after the page has been loaded may overwrite the entire page, so modification of the specified DOM element is usually given priority.
JavaScript array
JavaScript arrays are variable in length, and different types of values can be held in the same array.
Use array literals
const array = [10, 20, 30];
for (let i = 0; i < array.length; i++) {
console.log("数组索引:" + i + ",数组元素:" + array[i]);
}Create an array of specified length
const array = new Array(3);
array[0] = 100;
array[1] = 200;
array[2] = 300;new Array(3) Create a length of 3 an empty slot array of, which does not contain numbers 3 array of.
Use a constructor to initialize an element
const array = new Array(1000, 2000, 3000);
for (let i = 0; i < array.length; i++) {
console.log("数组索引:" + i + ",数组元素:" + array[i]);
}Common array properties and methods
-
length: Array length. -
concat(): Connects the array and returns the new array. -
join(): Connects elements by the specified delimiter and returns a string. -
push(): Add elements at the end of the array. -
pop(): Delete and return the elements at the end of the array. -
reverse(): reverses the order of elements in the current array.
const array1 = [10, 20, 30];
const array2 = new Array(100, 200, 300);
array1.push(1);
array1.push(2);
array1.push(3);
array2.pop();
const array3 = array1.concat(array2);
console.log("数组长度:" + array3.length);
array3.reverse();
const text = array3.join("_");
console.log("数组转字符串:" + text);JavaScript function
function declaration
function add(value1, value2) {
return value1 + value2;
}function expression
const multiply = function (value1, value2) {
return value1 * value2;
};arrow functions
const divide = (value1, value2) => value1 / value2;Call example:
let result = add(10, 20);
result = multiply(10, 20);
result = divide(10, 20);
console.log("结果:" + result);Function parameters and return values do not need to be declared fixed types in the syntax, but runtime values still have types.
Dynamically create functions
JavaScript can be used Function Constructors dynamically create functions:
const parameters = "name, age";
const body = "console.log('name:' + name + ',age:' + age);";
const createdFunction = new Function(parameters, body);
createdFunction("张三", 20);This method requires parsing strings at runtime, is usually not as clear as ordinary functions, and may pose security risks, so it should be used with caution in actual development.
Script location and page loading
If the script is executed before the target element, the relevant DOM element may not have been created yet. Common solutions include:
-
will
<script>on<body>Before ending the label. -
Using on external scripts
deferAttributes. -
listening
DOMContentLoadedorloadevents.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>页面加载</title>
<script>
window.onload = function () {
const input = document.getElementById("v1");
console.log("编辑框对象:", input);
console.log("编辑框中的数据:" + input.value);
};
</script>
</head>
<body>
数据:<input id="v1" type="text" value="这是一个数据" />
</body>
</html>When the original code directly outputs an element object, what you get is the object description; to read the content of the input box, you need to access it. value Attributes.
JavaScript and function overloading
JavaScript does not support Java-style function overloading. When a function with the same name is repeatedly declared in the same scope, the subsequent definition will usually override the previous definition.
Different logic can be performed within a function based on the number of arguments or parameter types. This is just manual dispatch, not a real function overloading:
function showInfo() {
if (arguments.length === 0) {
console.log("无参数调用");
} else if (arguments.length === 1) {
console.log("一个参数:" + arguments[0]);
} else if (arguments.length === 2) {
console.log("两个参数:" + arguments[0] + "," + arguments[1]);
}
}
showInfo(100, 200);BOM Browser Object Model
BOM is used to operate browser windows and related functions, such as address bars, timers, pop-ups, and window jumps. in the browser window Is a global object, many methods can be omitted window. Prefix.
timer
-
setInterval(): Repeat execution of the function at specified time intervals. -
clearInterval(): Stop bysetInterval()Created timer. -
setTimeout(): Wait a specified time and execute the function once. -
clearTimeout(): Cancel delayed tasks that have not yet been executed.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>定时器</title>
<script>
let intervalId;
let timeoutId;
function updateTime() {
const date = new Date();
const span = document.getElementById("spanId");
span.innerText = date.toLocaleString();
}
function startInterval() {
if (intervalId === undefined) {
intervalId = setInterval(updateTime, 1000);
}
}
function stopInterval() {
clearInterval(intervalId);
intervalId = undefined;
}
function startTimeout() {
timeoutId = setTimeout(function () {
alert("定时任务开始执行");
}, 3000);
}
function stopTimeout() {
clearTimeout(timeoutId);
}
</script>
</head>
<body>
<div style="width: 600px; height: 300px; text-align: center;">
<span id="spanId"></span>
<hr />
<button onclick="startInterval()">开始更新时间</button>
<button onclick="stopInterval()">停止更新时间</button>
<hr />
<button onclick="startTimeout()">启动延时任务</button>
<button onclick="stopTimeout()">取消延时任务</button>
</div>
</body>
</html>Passing functions into the timer is clearer than passing strings and avoids extra string parsing.
Information pop-up window
-
alert(): Display a prompt message. -
confirm(): Display a confirmation box and return a boolean value. -
prompt(): Display the input box and return the entered string ornull。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>弹窗示例</title>
<script>
function deleteData() {
if (confirm("是否确认执行删除操作?")) {
console.log("执行删除功能");
}
}
function calculate() {
const number1 = prompt("请输入第一个数");
const number2 = prompt("请输入第二个数");
if (number1 !== null && number2 !== null) {
console.log("结果:" + (Number(number1) + Number(number2)));
}
}
</script>
</head>
<body>
<button onclick="deleteData()">删除</button>
<button onclick="calculate()">运算</button>
</body>
</html>opens in new window
Parent page:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>父窗口</title>
<script>
function createWindow() {
window.open("demo9.html", "", "width=600,height=700");
}
</script>
</head>
<body>
姓名:<input type="text" id="inp_name" /><br />
年龄:<input type="text" id="inp_age" /><br />
<button onclick="createWindow()">选择数据</button>
</body>
</html>Subpages can be accessed through window.opener Access the parent window that opened it:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>子窗口</title>
<script>
function selectData() {
const selected = document.querySelector('input[name="select"]:checked');
if (!selected || !window.opener) {
return;
}
const row = selected.closest("tr");
const cells = row.children;
const name = cells[1].innerText;
const age = cells[2].innerText;
window.opener.document.getElementById("inp_name").value = name;
window.opener.document.getElementById("inp_age").value = age;
}
</script>
</head>
<body>
<table border="1" width="500">
<tr>
<th>选择</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<tr>
<td><input type="radio" name="select" checked /></td>
<td>刘备</td>
<td>20</td>
</tr>
<tr>
<td><input type="radio" name="select" /></td>
<td>关羽</td>
<td>19</td>
</tr>
<tr>
<td><input type="radio" name="select" /></td>
<td>张飞</td>
<td>18</td>
</tr>
</table>
<button onclick="selectData()">获取选择的数据</button>
</body>
</html>Browsers may block new windows that are not directly triggered by user actions, and cross-source pages cannot access each other’s DOM at will.
page address
window.location Represents the current page address, which can be modified location.href Jump:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>页面跳转</title>
<script>
function visitAddress() {
const address = document.getElementById("inputId").value;
location.href = address;
}
</script>
</head>
<body>
访问地址:<input type="text" id="inputId" />
<button onclick="visitAddress()">访问</button>
</body>
</html>
If you enjoyed this, leave a comment~