Java之JavaScript详解(No.24)
1、JavaScript
? JavaScript是一门流行的脚本语言,一个合格的后端编程人员,必须要精通JavaScript。
? ECMAScript是JavaScript的一个标准。其目前最新版为ES6,但大部分浏览器还停留在只支持ES5版本代码(一般容易会出现“开发环境”与“上线环境”版本不一致的问题)。
? 使用JavaScript时,需熟练掌握并运用浏览器开发者工具中最常用四个功能模块。
2、两种JavaScript导入方式(Two JavaScript Import Methods)
2.1、JavaScript内部导入方式(JavaScript Internal Import Method)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript内部导入方式</title>
<script type="text/javascript">
alert("\"JavaScript内部导入方式!\"");
</script>
</head>
<body>
</body>
</html>
2.2、JavaScript外部导入方式(JavaScript External Import Method)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript外部导入方式</title>
<script src="../../../javascript/JavaScript外部导入方式.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
? 其JavaScript示例代码,如下所示。
alert("\"JavaScript外部导入方式!\"");
3、JavaScript基本语法(JavaScript Basic Grammar)
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript基本语法</title>
<script>
var score=90;
if(score>=0 && score<60){
alert("0~59");
}else if(score>=60 && score<90){
alert("60~89");
}else if(score>=90 && score<=100){
alert("90~100");
}else{
alert("不在0~100之间");
}
console.log(score);
</script>
</head>
<body>
</body>
</html>
4、JavaScript严格检查格式(JavaScript Strict Check Format)
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript严格检查格式</title>
<script>
"use strict";
for (var i = 0; i < 10; i++) {
console.log(i + 1);
}
console.log(i + 1);
for (let j = 0; j < 10; j++) {
console.log(j + 1);
}
console.log(j + 1);
</script>
</head>
<body>
</body>
</html>
5、JavaScript数据类型(JavaScript Data Type)
5.1、字符串(String)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>字符串</title>
</head>
<body>
<script>
var escapeCharacter1="\'";
console.log(escapeCharacter1);
var escapeCharacter2="\r";
console.log(escapeCharacter2);
var escapeCharacter3="\n";
console.log(escapeCharacter3);
var escapeCharacter4="\t";
console.log(escapeCharacter4);
var escapeCharacter5="\u4e2d";
console.log(escapeCharacter5);
var escapeCharacter6="\x43";
console.log(escapeCharacter6);
var multiLineString= `多
行
字
符
串`;
console.log(multiLineString);
var templateString="模板字符串";
var msg=`这是${templateString}`;
console.log(msg);
var stringLength=msg.length;
console.log(stringLength);
console.log(msg[0]);
msg[0]="那";
console.log(msg[0]);
var stringUpperCase="1aBcDe".toUpperCase();
console.log(stringUpperCase);
var stringLowerCase="2AbCdE".toLowerCase();
console.log(stringLowerCase);
var stringIndexOf="123456789".indexOf("1");
console.log(stringIndexOf);
var stringSubstring1="123456789".substring(0);
console.log(stringSubstring1);
var stringSubstring2="123456789".substring(0,3);
console.log(stringSubstring2);
</script>
</body>
</html>
5.2、数组(Array)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数组</title>
</head>
<body>
<script>
var arr1 = [1, "1", null, false];
console.log(arr1.length);
var arr2 = new Array("1", 1, 5, 3, 9, 7, null, true);
console.log(arr2.length);
var arrIndex = arr1.indexOf("1");
console.log(arrIndex);
var arr3 = arr2.slice(1, 7);
console.log(arr3);
arr3.push(['push']);
console.log(arr3);
arr3.pop();
console.log(arr3);
arr3.unshift(['unshift']);
console.log(arr3);
arr3.shift();
console.log(arr3);
arr3.sort();
console.log(arr3);
arr3.reverse();
console.log(arr3);
var arr4 = arr3.concat([8, 2, 6]);
console.log(arr4);
console.log(arr4.join('-').substring(1,arr4.join('-').length));
var arr5=[[1,'a'],[2,"b"],[3,false]];
console.log(arr5[1][1]);
var arr6=new Array([1,'a'],[2,"b"],[3,false])
console.log(arr6[1][1]);
</script>
</body>
</html>
5.3、对象(Object)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>对象</title>
</head>
<body>
<script>
var person={
id:1,
name:"xueshanxuehai",
age:22,
mobilephone:"12345678901"
}
console.log(person);
person.name="学山学海";
console.log(person);
console.log(person.job);
delete person.name;
console.log(person);
person.job="Java后台";
console.log(person);
console.log('name' in person);
console.log('job' in person);
console.log('toString' in person);
console.log(person.hasOwnProperty('job'));
console.log(person.hasOwnProperty('toString'));
</script>
</body>
</html>
5.4、流程控制(Process Control)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>流程控制</title>
</head>
<body>
<script>
var age=22;
if(age>=0 && age<=59){
console.log("0~59");
}else if(age>=60 && age<=100){
console.log("0~59");
}else{
console.log("不在0~100之间");
}
age=20;
while(age<100){
age++;
console.log(age);
}
age=30;
do{
age++;
console.log(age);
}while(age<100);
for (let i = 0; i < 100; i++) {
console.log(i+1);
}
var fe=[1,2,3,2,1];
fe.forEach(function (value) {
console.log(value);
})
fe.forEach(function (value, index, array) {
console.log(value, index, array);
});
for (const feKey in fe) {
if(fe.hasOwnProperty(feKey)){
console.log("数组自身拥有的元素:"+fe[feKey]);
}
}
var forIN={
id:1,
name:"For-In",
f1:"F1",
f2:"F2",
f3:"F3"
}
for (const forINKey in forIN) {
if(forIN.hasOwnProperty(forINKey)){
console.log("对象自身拥有的属性:"+forIN[forINKey]);
}
}
</script>
</body>
</html>
5.5、Map和Set。
? Map和Set是ES6的新特性。
? Map 是一组键值对的结构,具有极快的查找速度。
? Set 和Map 类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set 中,没有重复的key。要创建一个Set ,需要提供一个Array 作为输入,或者直接创建一个空Set 。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Map和Set</title>
</head>
<body>
<script>
var mapCollection=new Map([['001',1],['005',5],['002',2],['001',4]]);
console.log(mapCollection);
console.log(mapCollection.get('001'));
mapCollection.set('004',4);
console.log(mapCollection);
mapCollection.delete('002');
console.log(mapCollection);
console.log(mapCollection.has('004'));
var setCollection=new Set(['001','005','003','001']);
setCollection.add(1);
console.log(setCollection);
setCollection.delete('003');
console.log(setCollection);
console.log(setCollection.has(1));
</script>
</body>
</html>
5.6、Iterator。
? Iterator是ES6的新特性。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Iterator</title>
</head>
<body>
<script>
var iterArr=[1,5,9,2,6];
for (const number of iterArr) {
console.log(number);
}
var iterMap=new Map([['1',1],['5',5],[1,1],['3',3]]);
for (const iterMapElement of iterMap) {
console.log(iterMapElement);
}
var iterSet=new Set(['1','7',5,3]);
for (const iterSetElement of iterSet) {
console.log(iterSetElement);
}
</script>
</body>
</html>
6、JavaScript函数(JavaScript Function)
6.1、函数定义(Function Definition)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>函数定义</title>
</head>
<body>
<script>
function abs1(x) {
if(x>=0){
return x;
}else{
return -x;
}
}
console.log(abs1(11));
console.log(abs1(-11));
var abs2=function (x) {
if(x>=0){
return x;
}else{
return -x;
}
}
console.log(abs2(11));
console.log(abs2(-11));
var abs3=function (x) {
if((typeof x)!=='number'){
throw 'Not A Number';
}
if(x>=0){
return x;
}else{
return -x;
}
}
var abs4=function (x,...rest) {
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
if(x>=0){
return x;
}else{
return -x;
}
}
console.log(abs4(-11,1,2,3,['1',1],[2]));
</script>
</body>
</html>
6.2、变量作用域(Variable Scope)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>变量作用域</title>
</head>
<body>
<script>
function f1() {
var x = 1;
}
function f2() {
var x = 2;
return x;
}
function f2_1() {
var x = 3;
return x;
}
console.log(f2());
console.log(f2_1());
function f3() {
var x = 4;
function f3_1() {
var y = x + 1;
return y
}
console.log(f3_1());
return x;
}
console.log(f3());
function f4() {
var x = 5;
function f4_1() {
var x = 5.1;
return x;
}
console.log(f4_1());
return x;
}
console.log(f4());
function f5() {
var x = "x" + y;
console.log(x);
var y = "y";
return y;
}
console.log(f5());
function f5_1() {
var y = "y", x = "x" + y;
console.log(x);
return y;
}
console.log(f5_1());
var x = "全局变量";
function f6() {
console.log(x);
}
f6();
console.log(x);
console.log(window.x);
window.alert = function () {};
window.alert(x);
var myApp={};
myApp.name="xueshanxuehai";
myApp.add=function (a,b) {
return a+b;
}
console.log(myApp);
console.log(myApp.name);
console.log(myApp.add(1,2));
function f7_1() {
for (var i = 0; i < 10; i++) {
console.log(i+1);
}
console.log(i+1);
}
f7_1();
function f7_2() {
for (let i = 0; i < 10; i++) {
console.log(i+1);
}
}
f7_2();
var PI1="3.14159";
console.log(PI1);
PI1="3.14";
console.log(PI1);
const PI="3.1415";
console.log(PI);
</script>
</body>
</html>
6.3、方法定义(Method Definition)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>方法定义</title>
</head>
<body>
<script>
var person1={
name:"xsxh",
birthYear:1991,
age:function () {
var nowYear=new Date().getFullYear();
return nowYear-this.birthYear;
}
};
console.log(person1.name);
console.log(person1.age());
function getAge() {
var nowYear=new Date().getFullYear();
return nowYear-this.birthYear;
}
var person2={
name:"xsxh",
birthYear: 1991,
age:getAge
};
console.log(person2.name);
console.log(person2.age());
var person3={
name:"学山学海",
birthYear:2001,
age:getAge
}
console.log(getAge.apply(person2,[]));
console.log(getAge.apply(person3,[]));
</script>
</body>
</html>
7、JavaScript内部对象(JavaScript Internal Object)
7.1、标准对象(Standard Object)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>标准对象</title>
</head>
<body>
<script>
console.log(typeof 123);
console.log(typeof 123.321);
console.log(typeof '123.123');
console.log(typeof true);
console.log(typeof NaN);
console.log(typeof []);
console.log(typeof {});
console.log(typeof Math.abs);
console.log(typeof undefined);
</script>
</body>
</html>
7.2、Date对象(Date Object)。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date对象</title>
</head>
<body>
<script>
var nowDate = new Date();
console.log(nowDate);
console.log(nowDate.getFullYear());
console.log(nowDate.getMonth());
console.log(nowDate.getDate());
console.log(nowDate.getDay());
console.log(nowDate.getHours());
console.log(nowDate.getMinutes());
console.log(nowDate.getSeconds());
console.log(nowDate.getMilliseconds());
console.log(nowDate.getTime());
var timeStamp = nowDate.getTime();
nowDate = new Date(timeStamp);
console.log(nowDate);
console.log(nowDate.toLocaleString());
console.log(nowDate.toUTCString());
</script>
</body>
</html>
7.3、JSON对象(JSON Object)。
? JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
? 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
? 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
? 在JavaScript中,一切皆为对象,任何JavaScript支持的类型都可以用JSON来表示。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON对象</title>
</head>
<body>
<script>
var javaScriptObject={id:1,name:"JavaScript"};
console.log(javaScriptObject);
console.log(JSON.stringify(javaScriptObject));
var jsonObject='{"id":2,"name":"JSON"}';
console.log(jsonObject);
console.log(JSON.parse(jsonObject));
var javaScriptArr=[[{k11:"v11"},{k12:"v12"}],[{k21:"v21"},{k22:"v22"}]];
console.log(javaScriptArr);
console.log(JSON.stringify(javaScriptArr));
var jsonArr='[[{"k11":"v11"},{"k12":"v12"}],[{"k21":"v21"},{"k22":"v22"}]]';
console.log(jsonArr);
console.log(JSON.parse(jsonArr));
</script>
</body>
</html>
8、JavaScript面向对象编程(JavaScript Object-Oriented Programming)
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript面向对象编程</title>
</head>
<body>
<script>
var dog={
name:"小黄",
age:1,
run:function () {
console.log(this.name+","+this.age+",run");
}
};
var dog1={name:"小红"};
console.log(dog1);
dog1.___Proto___=dog;
console.log(dog1);
var bird={
fly:function () {
console.log(this.name+","+this.age+",fly");
}
}
dog1.___Proto___=bird;
console.log(dog1);
class Dog{
constructor(name) {
this.name=name;
}
run(){
alert('Run');
}
}
class Dog1 extends Dog{
constructor(name,age) {
super(name);
this.age=age;
}
getAge(){
alert('getAge');
}
}
var d1=new Dog("小红");
console.log(d1);
var d2=new Dog1("小黄",1);
console.log(d2);
</script>
</body>
</html>
9、JavaScript操作BOM对象(JavaScript Manipulate BOM Objects)
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript操作BOM对象</title>
</head>
<body>
<dl id="app">
<dt>HTML5</dt>
<dt>CSS3</dt>
<dt>JavaScript</dt>
</dl>
<script>
console.log(window.innerWidth);
console.log(window.innerHeight);
console.log(window.outerWidth);
console.log(window.outerHeight);
console.log(navigator.appName);
console.log(navigator.appVersion);
console.log(navigator.appCodeName);
console.log(navigator.userAgent);
console.log(navigator.platform);
console.log(screen.width);
console.log(screen.height);
console.log(document.title);
document.title="baidu";
console.log(document.title);
var mydl=document.getElementById("app");
console.log(mydl);
var mycookie=document.cookie;
console.log(mycookie);
</script>
</body>
</html>
10、JavaScript操作DOM对象(JavaScript Manipulate DOM Objects)
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript操作DOM对象</title>
</head>
<body>
<p id="add">add</p>
<p id="append">Append</p>
<div id="div">div1</div>
<div id="father">
<h1>h1</h1>
<p id="p1">p1</p>
<p class="p2">p2</p>
</div>
<script>
var h1=document.getElementsByTagName("h1");
var p1=document.getElementById("p1");
var p2=document.getElementsByClassName("p2");
var father=document.getElementById("father");
var fatherNodes=father.children;
console.log(fatherNodes);
var div=document.getElementById("div");
div.innerText="div";
div.innerHTML="<Striong>DIV</Striong>";
div.style.color="red";
div.style.fontSize="20px";
div.style.padding="2em";
var newPNode=document.createElement("p");
newPNode.id="newPNode";
newPNode.innerText="PNode";
father.insertBefore(newPNode,p2.item(0));
var addNode=document.getElementById("add");
var newJavaScript=document.createElement("script");
newJavaScript.setAttribute("type","text/javascript");
newJavaScript.innerHTML="father.appendChild(addNode);";
document.getElementsByTagName("head")[0].appendChild(newJavaScript);
var newCSS=document.createElement("style");
newCSS.setAttribute("type","text/css");
newCSS.innerHTML="body{background-color:green}";
document.getElementsByTagName("head")[0].appendChild(newCSS);
</script>
</body>
</html>
11、JavaScript操作表单(JavaScript Manipulate Form)
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript操作表单</title>
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
</head>
<body>
<form action="https://www.baidu.com" method="post" onsubmit="return md5PWD()">
<p>
<span>用户名:</span>
<input type="text" id="username" name="username"/>
</p>
<p>
<span>密码:</span>
<input type="password" id="input-password" name="password">
</p>
<input type="hidden" id="md5-password" name="password">
<p>
<span>性别:</span>
<input type="radio" name="sex" value="man" id="boy"/>男
<input type="radio" name="sex" value="women" id="girl"/>女
</p>
<button type="submit" onclick="md5PWD()">提交</button>
</form>
<script>
var username_text = document.getElementById("username");
var boy_radio = document.getElementById("boy");
var girl_radio = document.getElementById("girl");
console.log(username_text.value);
username_text.value = "123";
console.log(boy_radio.checked);
boy_radio.checked = true;
var uid = document.getElementById("username");
console.log(uid.value);
var input_pwd = document.getElementById("input-password");
console.log(input_pwd.value);
var md5_pwd = document.getElementById("md5-password");
console.log(md5_pwd.value);
function md5PWD() {
input_pwd.value = md5(input_pwd.value);
md5_pwd.value = input_pwd.value;
console.log(md5_pwd.value);
return true;
}
</script>
</body>
</html>
12、JQuery
? 一般称为“JQuery库”,其含有很多JavaScript函数,类似于“工具类”,在线帮助文档。
12.1、JQuery导入方式。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery导入方式</title>
<script src="../lib/jquery-3.6.0.js"></script>
</head>
<body>
<a href="" id="import-jquery">使用JQuery</a>
<script>
$('#import-jquery').click(function () {
alert("JQuery");
})
</script>
</body>
</html>
12.2、JQuery选择器。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery选择器</title>
<script src="../lib/jquery-3.6.0.js"></script>
</head>
<body>
<a href="">标签选择器</a>
<hr/>
<h id="id1">ID选择器</h>
<hr/>
<p class="class1">CLASS选择器</p>
<script>
$("a").click(function () {
alert("标签选择器");
});
$("#id1").click(function () {
alert("ID选择器");
});
$(".class1").click(function () {
alert("CLASS选择器");
});
</script>
</body>
</html>
12.3、JQuery事件。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery事件</title>
<script src="../lib/jquery-3.6.0.js"></script>
<style>
#divMove{
width: 500px;
height: 500px;
border: 1px solid red;
}
</style>
</head>
<body>
mouse:<span id="mouseMove"></span>
<div id="divMove">
移动鼠标试试
</div>
<script>
$(function () {
$("#divMove").mousemove(function (e) {
$("#mouseMove").text("x:"+e.pageX+",y:"+e.pageY);
});
});
</script>
</body>
</html>
12.4、JQuery操作DOM。
? 其HTML示例代码,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery操作DOM</title>
<script src="../lib/jquery-3.6.0.js"></script>
</head>
<body>
<ul id="ul1">
<li class="li1">JavaScript</li>
<li name="jquery">JQuery</li>
</ul>
<script>
console.log($("#ul1 li[name=jquery]").text());
console.log($("#ul1 li[name=jquery]").text("JQUERY"));
$("#ul1 li[name=jquery]").css({"color":"blue"});
$("#ul1 li[name=jquery]").hide();
console.log($(window).width);
console.log($(window).height);
$("#ul1 li[name=jquery]").toggle();
</script>
</body>
</html>
13、学习经验
? 巩固HTML+CSS:多模仿学习其它的优秀网站源码。
? 巩固JavaScript:多模仿学习JQuery源码与游戏源码。
|