JavaScript入门
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);