JavaScript入門
阿新 • • 發佈:2020-08-05
JavaScript介紹
JavaScript歷史
- 誕生於1995年 網景公司 第一代網際網路公司
- 建立人 布蘭登·艾奇
JavaScript和ECMAScript關係
網景公司開發 JavaScript
微軟公司開發 JScript
互相競爭
ECMAScript是一種語言標準,JavaScript是對ECMAScript的一種實現。
目前大部分瀏覽器執行的ECMA執行的都是2011年到2015年之間的,
JS語言的核心是ECMAScript。
如何引入JS檔案
內部的引入js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>js檔案的引入</title> <script type="text/javascript"> //編寫js程式碼 </script> </head> <body> </body> </html>
引入外部js檔案
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>js檔案的引入</title> <script type="text/javascript" src="js/index.js"> //編寫js程式碼 </script> </head> <body> </body> </html>
alert 彈框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>js檔案的引入</title> <script type="text/javascript" src="js/index.js"> //編寫js程式碼 </script> </head> <body> alert("呵呵"); </body> </html>
變數
變數初始化
宣告變數 var x = 30;
變數賦值var y;
y = 50;
變數 必須 使用字母、下劃線(_)$開始
多個英文字母 遵循駝峰 myName
不能使用js中的關鍵字和保留字來進行命名。
變數名嚴格區分大小寫
var _A = 50;
var $ = 90;
alert(_A);
變數型別
基本的資料型別
Number String Boolean undefined null
引用的資料型別
Object Array Function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>aaa</title>
</head>
<body>
<script>
var a = 3;
var b = 3.14;
var c = -1;
alert(typeof a); //typeof 檢驗變數的型別
alert(typeof b);
alert(typeof c);
//字串 abc234
var d = 'abc';
var e = '234';
alert(typeof d);
alert(typeof e);
//布林值
var f = 3 < 4;
alert(f);
alert(typeof f);
var g = 3 > 4;
alert(g);
alert(typeof g);
//宣告變數
var x;
alert(x);
alert(typeof x);
</script>
</body>
</html>
運算子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>算數運算子</title>
</head>
<body>
<script>
var x = 10;
var y = 2;
var sum = x + y;
var en = x - y;
var or = x * y;
var op = x % y;
alert(sum);
alert(en);
</script>
</body>
</html>
遞增和遞減以及賦值運算子
var x = 3
//x++;
x = x + 1
alert(x);
var a = 5;
var b = 6;
a = b;
var c = 10;
//c+=5;
c = c+ 5;
字串
var str = 'sdaddada';
注意點:字串巢狀
字串拼接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>字串的拼接</title>
</head>
<body>
<script>
var a = '123';
var b = '456';
//字串的拼接
var sum = a + b;
alert(sum);
</script>
</body>
</html>
數字與字串拼接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>字串的拼接</title>
</head>
<body>
<script>
var a = 'javascript' + 123
//字串的拼接
alert(a);
alert(typeof(a));
</script>
</body>
</html>
陣列
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>陣列</title>
</head>
<body>
<script>
//建立陣列
var a = [1,2,3,4,5];
//建立商品陣列
var b = ['香蕉','牛奶','蘋果'];
alert(a);
alert(b);
alert(typeof a);
alert(typeof b);
//在Console中打印出來
console.log(a);
//二維陣列
var c = ['汽車','飛機',b];
console.log(c);
//訪問陣列內的內容
var item1 = a[0]
console.log('item1',item1);
//取二維陣列資料
var d = c[2][2];
console.log(d);
//訪問陣列長度
console.log(c.length);
</script>
</body>
</html>
條件判斷
if ......else
if(1 > 2){
alert(1);
}else{
alert(2)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>條件判斷</title>
</head>
<body>
<script>
var distance = 10;
if(5 < distance){
console.log("自動駕駛");
}else{
console.log("人為駕駛");
}
//多個條件
var weather = 'Sunny';
if (weather === 'Sunny'){
console.log('天氣好!出去玩')
}else if(weather === 'rainy'){
console.log("下雨了");
}else{
alert("輸入錯誤");
}
</script>
</body>
</html>
比較運算子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>比較運算子</title>
</head>
<body>
<script>
//=== 等同於!==
var a = 5;
var b = '5';
var c = a === b;
console.log(c);
var d = a == b;
console.log(d);
console.log(3 > 5);
console.log(3 >= 5);
console.log(3 < 4);
console.log(3 <= 5);
</script>
</body>
</html>
邏輯運算子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>邏輯運算子</title>
</head>
<body>
<script>
var weather = 'sunny';
var temp = 32;
if (weather === 'sunny'){
if (temp > 30){
console.log('太熱!待在家中');
}else{
console.log("天氣好!出去玩");
}
}
//&& 兩個條件都滿足
if (weather === 'sunny' && temp > 30){
console.log("在家");
}else if(weather === 'sunny' && temp <= 30){
console.log("chuqu ");
}
var m = 88;
var e = 90;
if(m >= 90 || e >= 85){
console.log("玩");
}else{
console.log("等");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>邏輯運算子</title>
</head>
<body>
<script>
var a = 1;
switch(a){
case 1:
alert(1);
break;
case 2:
alert(2);
break;
case 3:
alert(3);
break;
default:
break;
}
</script>
</body>
</html>
編寫switch語句小心break cash穿透
三元運算子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>三元運算子</title>
</head>
<body>
<script>
// if ...else
// (條件)? run this code: run this code;
var a = 1 > 2 ? '真的' : '假的';
alert(a);
</script>
</body>
</html>
迴圈
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>迴圈</title>
</head>
<body>
<script>
var arr = [1,2,3,4,5];
//如果我想取到裡面的值,我難道用arr[0],arr[1],arr[2],arr[3]
//當資料太多了!這種方法就不行了。
//我們用迴圈來拿資料
//for(初始化條件;結束條件;遞增條件){
//run this code
//}
var i;
var sum = 0;
for (i =1; i <1000; i++){
console.log(i);
sum = sum +i;
}
console.log(sum);
var shopping = ['香蕉','菠蘿','番茄','黃瓜'];
var j;
for(j=0; j < shopping.length;j++){
var g = '<h1>'+ shopping[j]+'</h1>'
document.write(g);
}
</script>
</body>
</html>
終止迴圈
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>終止迴圈</title>
</head>
<body>
<script>
var arr = [1,2,3,4,5];
for(i=10; i <=10; i--){
alert(i);
if(i <= 0){
break
}
}
var sum = 0;
for(var i = 1; i <= 10; i++){
if(i === 8){
//跳出當前迴圈,下次迴圈繼續進行
continue;
}
}
</script>
</body>
</html>
while迴圈
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>while迴圈</title>
</head>
<body>
<script>
//初始化條件
while(判斷迴圈結束條件){
//run this code
//遞增條件
}
var sum = 0;
var n = 99;
while(i<0){
sum = sum + n;
n = n -2
}
alert(sum);
</script>
</body>
</html>
do while
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>while迴圈</title>
</head>
<body>
<script>
// while寫法
//1 到100之間的數
var sum = 0;
var i = 1;
while (i <= 100){
sum = sum + i;
i++;
}
alert(sum);
//do while 寫法
//先執行,再判斷。
var sum = 0;
var i = 1;
do{
sum = sum + i;
i++;
alert(sum);
}while(i <= 100);
</script>
</body>
</html>
函式
函式的主要功能就是封裝程式碼。
function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>while迴圈</title>
</head>
<body>
<script>
function 函式名(){
//run this code
}
//呼叫
函式名();
</script>
</body>
</html>
函式的作用就是封裝重複性的程式碼。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函式</title>
</head>
<body>
<script>
function 做飯(isBad){
//run this code
if(isBad){
alert("點外賣");
}else{
alert("做菜");
}
}
var bad = true;
//呼叫
做飯(bad);
</script>
</body>
</html>
函式返回值和函式表示式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函式返回值和函式表示式</title>
</head>
<body>
<script>
//addition加法
//subtraction減法
//multiplication乘法
//division除法
function addition(a,b){
var r = a + b;
return r;
}
function subtracation(a,b){
var r = a - b;
return r;
}
function multiplication(a,b){
var r = a * b;
return r;
}
function division(a,b){
var r = a / b;
return r;
}
var r = addition(3,2);
console.log(r);
</script>
</body>
</html>
函式表示式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函式表示式</title>
</head>
<body>
<script>
//addition加法
//subtraction減法
//multiplication乘法
//division除法
var addition = function(a,b){
return a + b;
}
var a1 = addition(1,2);
console.log(a1);
</script>
</body>
</html>
函式作用域
使用匿名函式來解決函式全域性變數汙染的問題。
對於函式作用域就像在動物園中!每一個函式都在自己獨立的園區中。
園區管理員就是全域性的。
物件
物件擁有屬性和動作。
var person = {
name:"老王",
age:18,
sex:'男',
fav:function(age){
alert("愛好姑娘");
return '姑娘'+ age + '歲';
}
}
console.log(person);
console.log(person.name);
console.log(person.fav(18));
JavaScript 常用內建物件
var arr = [1,2,3];
內建物件 native object 物件:屬性和方法
documeng.write("哈哈哈");
<script>
//js提供建構函式
var colors = new Aeeay();
console.log(colors);
var colors2 = [];
colors2[0] = 'red';
colors2[1] = 'blue;
colors2[2] = 'yellow';
console.log(colors2);
if(Array.isArray(colors)){
//對資料進行操作
colors[0] = 'red';
var a = colors.toString();
}else{
}
</script>
分割字串
var colors = ['red','blue','green']
var a = colors.join('|');
console.log(a);
棧(lifo last-in-first-out)方法佇列方法
push() pop() 佇列方法
//push()
//往陣列的最後一項新增內容
var colors = [1,2,3,4];
var newlength = colors.push('aaaa');
console.log(newlength);
console.log(colors);
//pop()
//從陣列末尾刪除最後一項
var lastitem = colors.pop();
console.log(lastitem);
console.log(colors);
//佇列 fifo 先進先出 shift() unshift()
var newlength = colors.unshift("yellow");
var firstitem = color.shift();
陣列倒序
var a = [0,3,2,16,14];
var b = a.reverse();
console.log(b);
陣列排序
升序或者降序
var a = [0,3,2,16,14];
var b = a.sort();
console.log(b);
function compare(a,b){
if(a < b){
return -1;
}else if(a > b){
return 1;
}else{
return 0;
}
}
function compare(a,b){
if(a < b){
return 1;
}else if(a >b){
return -1;
}else{
return 0;
}
}
對陣列的操作方法
//操作方法
//concat() 數組合並
//slice() 切割 將當前陣列中的一個或者多個項建立一個新的陣列
//splice() 刪除 插入 替換
var c = [1,2,3,4];
var d = c.concat(5);
var e = c.concat({name:"張三"});
var f = c.concat({name:"張三"},[6,7])
var c = [1,2,3,4];
var d = c.slice(1);
var e = c.slice(1,2);
//刪除
var c = [1,2,3,4];
var d = c.splice(0,2) //從索引為的0地方開始刪除前兩項
// 插入
var d = c.splice(1,0,'熊大','jack');
console.log(d);
//替換
var d = splice(1,1,'xxx');
console.log(d);
迭代方法
filter
var number = [1,2,3,4,5];
var f = number.filter(function(item,index,array){
console.log(item);
console.log(index);
console.log(array);
return item = 20;
});
console.log(f);
map()方法
var n = [1,2,3,4,5];
var m = n.map(function(item,index,array){
return item*2;
})
console.log(m);
for(var i = 0l i < m.length; i++>){
console.log(m[i]);
}
forEach()
遍歷操作
var n = [1,2,3,4,5];
a = n.forEach(function(item,index){
console.log(a);
})
map 方法的應用
<script>
var old = [
{
name:"張三",
age:18,
},
{
name:"李四",
age:20,
},
{
name:"王五",
age:38,
}
];
var newNames = [];
var newAges = [];
for(var i = 0; i < old.length; i++>){
var myname = oldold[i].name;
var myage = newAges[i].age;
newNames.push(myname);
newAges.push(myage);
};
console.log(newNames);
console.log(newAges);
//另一種方法
var newNames = old.map(function(item,index){
return item.name
});
var newAges = old.map(function(item,index){
return item.age
});
</script>
字串的常用方法
<script>
//屬性
//length
//方法
/*
charAt()
charCodeAt()
concat()
slice()
substr()
substring()
indexOf()
lastIndexOf()
trim()
toLowerCase()
toLocaleLowerCase()
toUpperCase()
toLocaleUpperCase()
*/
</script>
字串的屬性
var str = 'helloworld';
console.log(str.length); //獲取字串的長度
字串的方法
var str = 'helloworld';
console.log(str.charAt(1));//獲取指定索引的字元
console.log(str.charCodeAt(1));//獲取指定索引的字元的ASCII碼
console.log(str.concat('jjj'));//拼接字串 ,通常不使用concat。
console.log(str.slice(2));//切片
console.log(str.substring(2));//切片
console.log(str.substr(2));//切片
//第一個引數是起始的位置,第二個引數是結束的位置,顧頭不顧尾。
console.log(str.slice(2,4));
console.log(str.substring(2,4));
//第二個引數是返回的字元數
console.log(str.substr(2,4));
console.log(str.slice(-3));
console.log(str.slice(-3,-1));//(8,10)
console.log(str.slice(8,10));
console.log(str.indexOf('o'));//從前往後找
console.log(str.lastIndexOf('o'));//從後往前找
//第一個字串查詢指定字元,第二個數字指定開始查詢索引位置
console.log(str.indexOf('o',6));
console.log(str.lastIndexOf('o',6));
console.log(str.trim());//清除當前字串的前後空格
console.log(str.toUpperCase());//字串轉大寫 常用
console.log(str.toLowerCase());//字串轉小寫 常用
字串常用方法案例
//查詢e在str中所有的位置
var str = '12adadadadadadadafgdsfeeefdfsdfeeeesfree';
var arr = [];
var pos = str.indexOf('e');
console.log(pos);
while(pos > -1){
//找到當前e的字元當前位置
arr.push(pos);
pos = str.indexOf('e',pos+1);
}
console.log(arr);
內建物件 日期物件 Date
var now = new Date();
console.log(now);
//傳參
var xmas = new.Date('December 25,1995 13:30L30');
console.log(xmas);
var xmas = new Date(1995,11,25);
console.log(xmas);
var xmas = new Date(1995,11,25,10,22,3);
console.log(xmas);
日期物件 Date常用方法
//常用方法
console.log(now.getDate());//獲取月份的第幾天
console.log(now.getMonth());//獲取月份
console.log(now.getFullYear());//獲取年份
console.log(now.getDay());//獲取一星期中的第幾天
console.log(now.getHours());//獲取小時
console.log(now.getMinutes());//獲取分鐘
console.log(mow.getSeconds());//獲取秒
日期格式化
console.log(now.toDateString());//星期天 月 日 年
console.log(now.toTimeString()); //時分秒
console.log(now.toLocaleDateString());
console.log(now.toLocaleTimeString());
console.log(now.toLocaleString());
console.log(now.toUTCString());
返回用數字時鐘格式的時間
//0-23
//6:27:35 P.M
//6:20:01 P.M
//6:04:01 P.M
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//18 >12 ? 18-12:8
var temp = ''+(hour > 12 ? hour -12 :hour);
console.log(temp);
if (hour === 0){
temp = '12';
}
temp = (minute < 10 ? ':0' : ":")+minute;
temp = (second < 10 ? ':0' : ":")+second;
temp = temp +(hour >= 12) ? 'P.M' : "A.M";
console.log(temp);
function nowNumTime(){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//18 >12 ? 18-12:8
var temp = ''+(hour > 12 ? hour -12 :hour);
console.log(temp);
if (hour === 0){
temp = '12';
}
temp = (minute < 10 ? ':0' : ":")+minute;
temp = (second < 10 ? ':0' : ":")+second;
temp = temp +(hour >= 12) ? 'P.M' : "A.M";
return temp;
}
var nownum = nowNumTime();
console.log(nownum);
字串和數值的相互轉換
var str = '123431231.1231231'
console.log(parseInt(str));//只會保留整數!小數會被忽略。
var str = '123123tyyyy123123';
console.log(parseInt(str));//碰到英文就停止
var str = '12131.123131';
console.log(parseFloat(str));//或真個浮點數
console.log(Number(str));//強制型別轉換,如果字串裡英文,報NaN錯誤。
var a = Number(str);
console.log(isNaN(a));//判斷當前數值是否是NaN。
var num = 2213.1231;
console.log(num.toString());//強制轉字串
console.log(String(num));//強制轉字串
//隱式轉換
console.log(''+ num);
console.log(''.concat(num));//不常用
console.log(num.toFixed());//不指定位數,保留整數!滿5進位,四捨五入。
console.log(num.toFixed(1));
Globle 物件
console.log(globle);
console.log(Globle);
//URI 通用資源識別符號
var uri = 'http://www.apelang.cn/web index.html?name=zhangsan';
console.log(encodeURI(uri));
console.log(encodeURIComponent(uri));//編碼使用最多的方法
var encodeuri = 'http://www.apelang.cn/web index.html?name=zhangsan';
console.log(decodeURI(encodeuri));
console.log(decodeURIComponent(encodeuri));//解碼經常使用
Window 物件
var a = 3;//它在全域性作用域下。
console.log(window.a);
function hello(){
alert(window.a);
}
window.hello();
hello();
Math 物件
//Math
Math.E
Math.LN10
Math.LN2
Math.LOG2E
Math.PI
Math.SQRT2//2的平方根
Math.SQRT_2
Math 方法
var max = Math.max(3,34,55,100);
var min = Math.max(3,2,1);
求陣列中的最大值
var arr = [1.2.3.4.5.6];
var arr_max = Math.max.apply(null,arr);
console.log(arr_max);
天花板函式
//向上取整
var num = 24.8;
var num_t = Math.ceil(num);
console.log(num_t);
地板函式
//向下取整
var num = 24.8;
var num_t = Math.floor(num);
console.log(num_t);
標準的四捨五入
var num = 24.8;
var num_t = Math.round(num);
console.log(num_t);
隨機數
console.log(Math.random());
獲取整數
//獲取min到max之間的整數
//Math.random()*(max-min)+min
function random(max,min){
return Math.floor(Math.random() * (max-min) + min);
}
//獲取隨機顏色
function randomColor(){
var r = random(0,256),g = random(0,256),b = random(0,256);
//模板字串
var result = 'rgb($(r),$(g),$(b))';
return result;
}
var rc = randomColor();
console.log(rc);
document.body.style.backgroundColor = rc;
//隨機驗證碼 四位 +字母(大寫)
function createCode(){
//設定預設的空字串
var code = '';
var codeLength = 4;
var randomCode = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
for(var i = 0; i < codeLength; i++){
//設定隨機範圍0-36
var index = random(0,36);
var code += randomCode[index];
}
return code;
}
var randcode = createCode();
console.log(randcode);
document.write('' + randcode);