模块五 前端JavaScript


js

js历史  布兰登.艾奇  
js与ECMAScript关系  JScript 微软、java无关  标准语言ECMAScript  js是对ECMAScript的一种实现  从ES4开始  ES6 
js组成 
| -- js核心语法
| -- DOM
| -- BOM

js文件引入 内部js 外部文件js src=‘js/index.js’ 顺序执行,一般在head部分,可以放在最后,加载完DOM后在运行js文件

变量
// 单行注释
/*  */ 多行注释
变量初始化
var x = 30;  
声明变量
var y;
变量赋值  
y = 50;

var name = '晚安';
1.必须使用字母下划线(_) $ 开始
2.多个英文字母 驼峰 myName 
3.不能使用js中的关键字和保留字来进行命名
4.严格区分大小写

var z = 40;
z = 50;
alert(z);
变量类型
基本的数据类型
number string boolean  undefined null
引用的数据类型
object array function

number数值类型
var a = 3;
var b = 1.234
var c = -1;
typeof 检查当前变量的数据类型
alert(typeof a);

字符串 单引号或者双引号 引用
var name = 'mjj'
var en = 'abc';
alert(typeof name);

Boolean  0  false  1  true
var c = 3 <= 4;
alert(c);
alert(typeof c);

声明变量  undefined   一般即声明并定义 var x = 'haha';   
var x;
alert(x);
alert(typeof x);

空对象 null
var y=null;
alert(y)
alert(typeof y);

运算符
算数运算符
+ - * / %  取余 ()  

递增 增减 以及赋值运算符
++
--
var x=3;
x = x+1
var a = 5;
var b = 6;
a = b;

c+=5;
c -=2;
c*=4;

字符串
var str = '#$%';
alert(str);
var word = 'hello';
var newWord = word;
altert(typeof word);
altert(newWord);
var name = 'would you eat a "aplle"';
转义
var str = "I'm \"mjj\"";
拼接
var joined = 'hello' + ' ' + 'mjj';
alert(joined)
数字和字符串
var a = 'mjj' + 521;
alert(typeof a);

var b = '18' + '40';
alert(typeof b);

字符串转换数值
1.隐式转换 数值转字符串
var num = 234;
var mystr = num + "";
alert(typeof mystr);

2.tostring() 数值转字符串
var mystr2 = num.tostring();

字符串转数值
var myNum = Number(num);

var  n = '2134fh';
var a = Number(n);
alert(typeof a);  // NaN     not a number 

数组Array  值的集合  == list 

var shopping = ['香蕉','苹果','牛奶','红牛']
alert(shopping);
alert(typeof shopping);
console.log(shopping);
var rand = ['tree','345'.[1,2,3]]; 二维数组
console.log(rand);

访问
var item1 =rand[0];
console.log(item1);
rand[0]='扭脸';
console.log(rand);
var a = rand[2][2];
console.log(a);

访问数组长度  for 
console.log('数组长度是:' + rand.length);

选择  50w
条件判断
if..else
if(条件)
{ 
}else{
}

var distance = 10;
var nowdistance = 5;
if (nowdistance < distance){
console.log('自动驾驶')
}else{
console.log('人为驾驶');
}

var weather = 'sssunny'
if(weather === 'sunny'){
console.log('天气好');
}else if(weather === 'rainy'){

}else if(weather === 'snowing' ){

}else {
alert('输入天气有错');
}

比较运算符  
=== 等同于比较值和数据类型    !==   严格比较  + 类型相同才为true
var a=5;
var saat = '5';
var isqual1 = a !== saat;
console.log(isqual1);
== 等于 只比较值不管数据类型   !=   不等于
var isqual2 = a == saat;   
console.log(isqual2); 

<= >=

逻辑运算符

var weather = 'sunny';
var temp = 32;

if (weather === 'sunny') {
if (temp > 30){
console.log('');
}else{
console.log('');
};
}else{
}

&& || !true

if(weather === 'sunny' && temp > 30){
console.log('xx');
}else if(weather === 'sunny' && temp <= 30 ){
console.log('xxx');
}

var mathsore = 66;
var emlishsore= 80;
if(mathsore >= 80 || emlishsore >=85){
   console.log('xx');
}else{
console.log('xx');
}


var isLogin = false;
if (!isLogin){
console.log('已登录');
}
switch语句
取代多条件判断
if(true){
}else if(){
}else if(){
}

switch(a){
case labe_1;
statement_1
break;
case labe_2;
statement_2
break;
default:
break;
}

var weather = 'suuny';
switch(weather){
case 'sunny';
alert(1);
break;
case 'rainy';
alert(2);
break;   # 编写switch语句  小心breakcash穿透
default:
alert(3);
break;
}
三元运算符 解决单判断
if....else..
条件 ? 真的 : 假的;
var isresult = 1 > 2 ? '真的' '假的'

对应  结果 =  条件成立时    if   条件   else   不成立 
        "臭不要脸" if "苍老师" in num else "正经人"

for循环 

for(初始化条件; 结束条件; 递增条件){
run this code
}

var i;
var sum = 0;
for(i=1;i<=1000;i++){
console.log(i);
sum = sum + i;

}
consolo.log(sum);

var shopping = ['教教','香蕉','牛奶','牛红']
var j;
for(j=0;j<shopping.length;j++){
// console.log(shopping[j]);
var htmlStr = <h1> + shopping[j] + </h1>‘;
console.log(htmlStr);
document.write(htmlStr);
}

996 

break & continue

死循环
var x = 0;
for(;;){
if(x>100){
break;  # 跳出当前循环
}
x++;
}
console.log(x);

var sum = 0;
for(var i=1;i<=10;i++){
if(i === 8){
// break;
continue;  # 跳出当前循环下次循环继续进行
}
sum = sum +i;
}
alert(sum);
while 循环  先判断再执行 
初始化条件
while(判断循环结束套件){
// run this code
递增条件
}

var sum =0;
var n = 99;
while (n>0){
sum = sum + n;
n = n -2;
}
alert(sum);


do while  先执行一次 在判断
var sum =0 ; 
var i  = 1;
while (i<=100){
sum = sum +i;
i++;
}
alert(sum);

var sum = 0'
var i = 1;
do{
sum = sum + i;
i ++;
console.log(i);
}while(i<= 1);
函数  解决重复代码  类似Python 
function 做饭(){

}
做饭();

函数传参
形式参数
function 做法(isbad,a,b,c,d){   
if(isbad){
}else{
};

}

var bad = false;
做饭(isbad);

返回值和表达式

function addition(a,b){
var r = a + b;
return r;
}

function subtraction(a,b){
return a - b;
}

function muliplicatio(a,b){
return a * b;
}

function division(a,b){
return a / b;
}
var r = addition(3,2
console.log(r);

没有return 返回undefined
函数表达式:
var division = function(a,b){
return a / b;
}

作用域和全局污染 
var a = 1;
console.log(a);
function add(){
var b = 3;
console.log(a);
}
add();
console.log(b);

全局污染 
全局变量会覆盖   相同函数在全局会被覆盖

first.js
(function(){
var name = 'mjj';
var hello = function(){
alert('hello' + name);
}
window.first = hello;
})();

second.js
(function(){
var name = 'mjj';
var hello = function(){
alert('hello' + name);
}
window.second = hello;
})();


<script src=js/first.js></script>
<script src=js/second.js></script>

console.log(window);
first();
second();

object对象
作用域
var name = '火腿肠';

function 老虎(){
alert(name);

}

function 企鹅(){
alert(name);
}
老虎();

对象 (属性和方法)  字面量创建  姓名年龄性别爱好(动作)  == 字典  key不需要加引号  'name': 123    person['name']
var person = {
name: 'mjj',
age : 18,
sex: '女',
fav:function(a){
alert('爱好')
return '姑凉' + a + '岁';
}

}
console.log(persion);
console.log(persion.name);
console.log(persion.fav(18));
内置对象Array     数组是内置对象 
var arr=[1,2,3];
内置对象 native object 对象  属性和方法
document.write('hehe');

Array  object 
字面量创建一样

js提供构造函数
var colors = new Array();
等同于
var colors2 = [];

# 判断是否是数组对象
if(Array.isArray(colors)){
对数组进行操作
colors[0] = 'red';
var a = colors.toString();   // 方法  数组转字符串
console.log(colors[0]);
console.log(colors.length);
}

数据常用的方法

var arr = [1,2,3,];
var a = arr.toString();
var b = arr.toLocaleString();
console.log(a);
console.log(b);

数组中可以存放对象

var persion1= {
toLocaleString:function(){
return 'mjj';
};

toString:function(){
return '么积极';
}
}
var persion2= {
toLocaleString:function(){
return 隔壁老王';
};

toString:function(){
return '隔壁老李';
}
}
var people = [persion1,person2];
console.log(people);
console.log(people.toString());  # 转换为字符串 
people.toLocaleString();

join 分割字符串
var colors = ['red','blue']
var a = colors.join(',');
console.log(a)
栈方法(lifo last-in-first -out 后进先出 push(0) pop(0)) 队列方法
colors.push('puerple')
push() 往数组最后一项添加内容
var newlegth = colors.push('purple')
console.log(newlegth);
console.log(colors)
pop()  从数组末尾删除最后一项
var lastItem = colors.pop();
console.log(lastItem);
console.log(colors);


队列 fifo 先进先出  shift() unshift()  == 后进先出  栈方法   
newlenth = colors.unshift('yellow');   # 在数组最开始添加内容
console.log(newlenth);
console.log(colors);
var firstItem = colors.shift();   # 删除数组第一个元素
console.log(colors);

注意:

栈按照先进后出的原则存储数据先进入的数据被压入栈底最后的数据在栈顶需要读数据的时候从栈顶开始读出数据
队列只允许在一端插入在另一端删除所以只有最早进入队列的元素才能最先从队列中删除故队列又称为先进先出线性表
这样看来栈是先入后出队是先入先出

1push()是用来在数组末端添加项并且返回添加后数组的长度
2pop()在数组末端移除项返回移除的数组元素
3unshift()在数组前端添加项并且返回添加后数组的长度
4shift()在数组的第一个项前端移除返回移除的数组元素

我们使用unshift()和shift()方法共同操作队列的时候输出结果是受影响的并不是队列不符合先进先出的原则
我们可以使用push()和shift()组合或者使用pop()和unshift()组合来使得队列的输出结果也是展示先进先出的效果
var queue = [];
    queue.unshift("队列1");
    queue.unshift("队列2");
    queue.unshift("队列3");
    console.log("这是队列");
    console.log(queue.unshift());
    console.log(queue.pop());
    console.log(queue.pop());
    console.log(queue.unshift());

数组排序

var values= [0,3,2,16,15,10]
倒序
values.reverse();
sort()  升序 排序  or 降序
values.sort();  默认升序  toString方法转字符串之后比较ASCII码  b.charCodeAt();   每位比较

function compare(a,b){
a位于b之前
if(a<b){
return -1;
}else if(a>b){
return 1;
}else{
return 0;
}

}

function compare1(a,b){
return a - b;
}

function compare2(a,b){
return b - a;
}

# 升序
values.sort(compare1);
console.log(values);

# 降序 
values.sort(compare2);
console.log(values);

降序 
字符 按照字母顺序排序
数组操作方法
concat()  slice()  splice()
数据合并 
var colors= ['red','blue']
var newColors = colors.concat('green');
newColors = colors.concat({name:'zhanmgsan'});

数据获取
slice() 将当前i数组中的一个或者多个项创建一个新数组
var newcolors = colors.concat({name:'list'},['black','purple']);
newcolors = newcolors.slice(1,2);  # 取头不取尾      类似list[] 分片[1:3]   取头不取尾
console.log(newcolors);

splice() 删除 插入 替换
删除
var names = ['张三''李四', 'mjjj','alex'];
names.splice(0,2);     张三','李四'  被删除
console.log(names);

插入
names.splice(1,0,'胸大','jace');

替换
names.splice(1,1,'胸大');

数组的位置方法  indexOf()  lastIndexOf()  从末尾往前查找
var names = 【‘张三’,‘mjj’,'赵六'】
alert(names.indexOf('mjj'));
alert(names.lastIndexOf('mjj'));
如果查不到结果 返回 -1 
用于查询当前元素是否在数组中 

迭代方法   类似 Python filter/map/reduce
filter()  将数组元素进行过滤
var numbers = [1,2,3,5,511,11,23];
var fileteResult = numbers.filter(function(item,index,array){
return item>10;
});

console.log(fileteResult);
map() 方法
var mapresult = numbers.map(function(item,index.array){
return item * 2;
})
console.log(mapresult);

for(var i =0 ;i<mapresult.length;i++){
console.log(mapresult[i]);
}

forEach()
mapresult.forEach(function(item.index.array){
console.log(item);
})

map方法应用
var oldArray= [
{
name : '张三',
age:17
},
{
name : '张二',
age:18
},
{
name : '张大',
age:19
}
]
var newName = [];
var newAge = [];
for(var i =0;i<oldArray.length;i++){
var myname = oldArray[i].name
var myage = oldArray[i].age
newNames.push(myname);
newAge.push(myage);
}

var newNames = oldArray.map(function(item,index){
return item.name;
})
var newAges = oldArray.map(function(item.index){
return item.age
})
console.log(newNames);
console.log(newAges);

字符串常用方法

属性
length
方法
charAt()
charCodeAt()
concat()

slice()
subString()
substr()


indexOf()
lastIndexOf()

trim()

常用
toLowerCase()
toUpperCase()

toLocaleLowerCase()
toLocaleUpperCase()

var str = 'hello world';
str.length;   获取字符串长度
str.charAt(1)  获取指定字符
str.charCodeAt() 获取指定字符对应的编码
str.concat('mjj');  拼接字符串  通常情况  不使用它做拼接使用 "+" 来多个字符串拼接


第一个参数是起始的位置第二个参数是结束的位置    顾头不顾尾   跟Python一样取前不取后
str.slice(2)
str.substring(2)
str.slice(-8,-2)

第二个参数是返回的字符数
str.substr(2,6)

str.indexOf('o')  返回索引值
str.indexOf('o'6)  从6开始找
str.lastIndexOf('o')  从后面开始找
str.lastIndexOf('o' 6) 倒序从6开始找

 str.trim()  清除字符串前后空格   类似space 

var str = hello mjj;
str.toUpperCase();
str.toLowerCase();

如何查找当前字符的所有位置

var str = 'He unfolded the map and set it on the floor.'
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);

for 

Date日志对象的创建方式

UTC  1970.1.1  285616
var now = new Date();
console.log(now);

var xma = new Date('December 25,1995 13:30:00');
var xmas = new Date(1995,11,25);
console.log(xmas);
var xmas = new Date(1995,11,25,14,30,0);

常用方法
var now = new Date();
console.log(now.getDate())   获取月份的第几天(1-31)
console.log(now.getMonth())   获取月份(0-11)
console.log(now.getFullYear())  获取年份
console.log(now.getDay())  获取一星期中的第几天(0-6)
console.log(now.getHours()) 获取小时(0-23);
console.log(now.getMinutes())   获取分钟(0-59)
console.log(now.getSeconds())   获取秒(0-59)

2018-09-10
日期格式化方法
now.toDateString() 星期几    
now.toTimeString() 

常用
now.toLocaleDateString() 
now.toLocaleTimeString() 
now.toLocaleString()   

now.toUTCString()
条件 ? 真的 : 假的;
var isresult = 1 > 2 ? '真的' '假的'

6:27:35 P.M.
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);
if(hour === 0){
temp = '12';
}
temp = temp + (minute < 10 ? ':0' : ":") + minute;
temp = temp + (second < 10 ? ':0' : ":") + second;
temp = temp + (hour >= 12 ? ' P.M.' : "A.M.") ;

return temp;
}
var nownum = nowNumTime();
console.log(nownum);

字符串你和数值相互转换
var str = '143231,21321';
转换整型
parseInt(str);
字符串转数值类型
console.log(parseFloat(str));
console.log(typeof parseFloat(str));
console.log(Number(str));  // NaN  解析错误
var  a = Number(str);
console.log(isNaN(a));

var num = 12121.99
强制类型转换
console.log(num.toString());
console.log(typeof num.toString());
console.log(String(num));

隐式转换
console.log('' + num);
console.log(''.concat(num));

数值 蓝色字符串 黑色

console.log(num.toFixed(2));   保留2位 字符串
Number(num.toFixed(2))

Globle对象
console.log(Globle);
console.log(globle);

URI 统一标准字符集

编码
var uri = 'http://www,baidu.com  index.html' 
encodeURI(uri);
encodeURIComponent(uri)  # 编码使用最多的方法

解码
decodeURI 只能识别空格
decodeURIComponent()
window对象  类似global对象上面有案例调用不同文件中的局部变量

var a = 3;
console.log(window.a);
function hello(){
alert(window.a);
}
window.hello();

Math对象

var a = 3;
Math.E
Math.LN10
Math.LN2
Math.PI
Math.SQRT2

方法
min() max()
var max = Math.max(1,2,34,56);
var max = Math.min(1,2,34,56);

var arr = [1,2,3,22,34,31];
var max = Math.max.apply(null, arr);
var min = Math.min.apply(null, arr);
var max = Math.max(arr[0],arr[[1],arr[2])

ceil()  floor() round()
var num = 24.3 
Math.ceil(num);  天花板函数  向上取整
Math.floor(num)  地板函数  向下取整
Math.round(num)  标准的四舍五入

随机数

random()   0<random<1 
Math.random()

1获取min到max之间的整数1-100
function random(max,min){
return Math.floor(Math.random() * (max-min) + min);
}

2获取随机颜色 rgb(0-255.0-255,0-255)
function randomColor(){
var r = random(0,256),g=random(0,256),b=random(0,256);
// 模板字符串``    or 字符串拼接 join方法 or '+'   
var result = `rgb(${r},${g},${b})`;
return result;

}
var rc = randomColor();
console.log(rc);
document.body.style.backgroundColor = rc;


3获取验证码  四位  数字 + 字母(大写)

function createCode(){
// 设置默认空的字符串
var code = '';
// 设置长度
var codeLength = 4;
var randomCode = [0,1,2,3,4,5,67,8,9,'A','B'....]
for(var i=0; i<codeLength;i++){
// 设置随机范围 0 - 36
var index = random(0,36);
code += randomCode[index];
}
return code;
}

var rndcode = createCode();
console.log(rndcode);
document.write('<h1>${rndcode}</h1>')

验证码
    def make_code(self,n=4):
        res = ''
        for i in range(n):
            s1 = str(random.randint(0,9))
            s2 = chr(random.randint(65,90))
            res += random.choice([s1,s2])
        return res



CRUD 增删改查
高级
原型与原型链深入剖析
闭包