JS基础
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js文件的引入</title> <!-- 内部的js --> <script type="text/javascript"> // 编写js代码 alert('我是mjj'); </script> <!-- 外部的js --> <script type="text/javascript" src='js/index.js'></script> </head> <body> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>变量</title> </head> <body> <script type="text/javascript"> // 单行注释 /* 多行注释 */ // 变量初始化 var x = 30; var X = 30; // 声明变量 var y; // 变量赋值 y = 50; var name = '王聪聪'; /* 1.必须使用字母、下划线(_) $开始 2.多个英文字母 驼峰 myName 3.不能使用js中关键字 和保留字来进行命名 4.严格区别大小写 */ var _A = 40; var $ = 90; // alert(_A); // alert($ ); // alert(x); // alert(X); var z = 40; z = 50; alert(z); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!-- 变量类型 基本的数据类型 Number String Boolean undefined null 引用的数据类型 Object Array Function --> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> // number数值类型 var a = 3; var b = 1.234; var c = -1; // typeof 来检查当前变量的数据类型 // alert(typeof a); // alert(typeof b); // alert(typeof c); // 字符串 string 'abc234' 或者是 "我是mjj" var name = 'mjj'; var en = "abc"; // alert(typeof name); // alert(typeof en); // boolean 0(假 false) 和1(真 true) var c = 3 <= 4; // alert(c); // alert(typeof c); // 声明变量 var x; // alert(x); // alert(typeof x); // 空对象 var y = null; alert(y); alert(typeof y); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>运算符-算数运算符</title> </head> <body> <script type="text/javascript"> var x = 10; var y = 4; var sum = x + y; var sum2 = 4 + 5 + x + y; var en = x-y; var or = x * y; var op = x % y * sum; alert(or); alert(op); var c = (x + sum) / 4 -3; alert(c); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>递增和递减以及赋值运算符</title> </head> <body> <script type="text/javascript"> // ++ // -- var x = 3; // x++; x = x + 1; // alert(x); var a = 5; var b = 6; a = b; var c = 10; // c = c + 5; c += 5; c -= 2; c *= 4; c /= 3; alert(c); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>字符串</title> </head> <body> <script type="text/javascript"> // var str = '@#$%^&*'; // alert(str); // var word = "hello"; // var newWord = word; // alert(typeof word); // alert(newWord); // var name = 'would you eat a "apple"?'; // alert(name); // var str = "I 'm "mjj""; // alert(str); // var one = 'hello'; // var name = 'mjj'; var joined = 'hello' +' ' + 'mjj'; alert(joined); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>数字和字符串</title> </head> <body> <script type="text/javascript"> /* var a = 'mjj' + 521; alert(a); alert(typeof a); */ /* var b = '18' + '40'; alert(b); alert(typeof b); */ // 1.隐式转换 数值转字符串 var num = 234; var myStr = num + ""; // alert(typeof myStr); // 2.toString() 数值转字符串 var myStr2 = num.toString(); // alert(typeof myStr2); // 字符串转数值 var myNum = Number(num); // alert(typeof myNum); var n = '2424fhfh'; var a = Number(n); alert(typeof a);//NaN Not a number </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>数组Array</title> </head> <body> <script type="text/javascript"> // 创建 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); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>条件判断</title> </head> <body> <script type="text/javascript"> /* var distance = 10; var nowDistance = 16; if ( nowDistance <= distance) { console.log('自动驾驶'); }else{ console.log('人为驾驶'); } */ var weather = 'rainyxxxxxx'; if (weather === 'sunny') { console.log('天气非常棒,可以出去玩耍'); }else if(weather === 'rainy'){ console.log('天气下雨了,在家里呆着'); }else if(weather === 'snowing'){ console.log('天气下雪了,可以出去滑雪'); }else{ alert('输入的天气有错,重新输入'); } </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>比较运算符</title> </head> <body> <script type="text/javascript"> // === 等同于 和 !== var a = 5; var astr = '5'; var isequal1 = a === astr; console.log(isequal1); // == 等于 和!= 不等于 var isequal2 = a == astr; console.log(isequal2); console.log(4 <= 4); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>逻辑运算符</title> </head> <body> <script type="text/javascript"> var weather = 'sunny'; var temp = 32; /* if (weather === 'sunny') { if (temp > 30) { console.log('在家里吹空调,吃西瓜'); }else{ console.log('天气非常好,可以出去玩耍了'); } } // && 逻辑与 并且 || 逻辑或 或者 !true */ if (weather === 'sunny' && temp > 30) { console.log('在家里吹空调,吃西瓜'); }else if(weather === 'sunny' && temp <= 30){ console.log('天气非常棒,可以出去玩耍了') } // 数学考过80 或者英语考过85 才可以玩游戏 var mathScore = 77; var enlishScore = 80; if (mathScore >= 80 || enlishScore >= 85) { console.log('可以玩游戏'); }else{ console.log('在家里写作业'); } var isLogin = false; alert(!isLogin); if (!isLogin) { console.log('用户已登录'); } </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>switch语句</title> </head> <body> <script type="text/javascript"> var weather = 'rainy'; switch (weather) { case 'sunny': alert(1); break; case 'rainy': alert(2); // 编写switch语句 小心break,cash穿透 break; case 'snowing': alert(3); break; default: alert(4); break; } </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>三元运算符</title> </head> <body> <script type="text/javascript"> // if...else // (条件) ? run this code : run this code; var isresult = 1 < 2 ? '真的' : '假的'; alert(isresult); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>for循环</title> </head> <body> <script type="text/javascript"> // 循环 来做1+2+3....+10000 // 1+2+3+....+10000 /* for(初始化条件;结束条件;递增条件){ //run this code } */ var i; var sum = 0; for(i = 1; i <= 10000;i++){ sum = sum + i; // sum = 1 ,i = 2 // sum = 3, i = 3 // sum = 6, i = 4 } console.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); } </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>break和continue</title> </head> <body> <script type="text/javascript"> // break 可以跳出当前循环 var x = 0; for(;;){ //死循环 if(x > 100){ break; } x++; } console.log(x); // 1+2+3+4+5+6+7+9+10 var sum = 0; for(var i = 1; i <= 10; i++){ if(i === 8){ // break; // 跳出当前循环,下次循环继续进行 continue; } sum = sum + i; } alert(sum); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>while循环</title> </head> <body> <script type="text/javascript"> /* 初始化条件 while(判断循环结束条件){ // run this code 递增条件 } */ /* var sum = 0; //计算的和 var n = 99; //初始的奇数 while (n > 0) { sum = sum + n; n = n - 2; } alert(sum); */ // do 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++; console.log(sum); }while(i <= 1); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>函数</title> </head> <body> <script type="text/javascript"> // 做饭 // 买菜 // 洗菜 // 切菜 // 炒菜 // 吃菜 // 洗碗 // 睡觉..... // 买菜 // 洗菜 // 切菜 // 炒菜 // 吃菜 // 洗碗 // 睡觉..... // 买菜 // 洗菜 // 切菜 // 炒菜 // 吃菜 // 洗碗 // 睡觉..... // 买菜 // 洗菜 // 切菜 // 炒菜 // 吃菜 // 洗碗 // 睡觉..... // 封装重复性代码 function 做饭(isBad,a,b,c) { //isBad 形式参数 alert(isBad); if(isBad){ alert('点个外卖'); }else{ // 买菜 // 洗菜 // 切菜 // 炒菜 // 吃菜 alert('做饭了'); } } var bad = true; //刀坏了 // 做饭(bad); // 洗碗 // 睡觉..... 做饭(bad); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>函数返回值和函数表达式</title> </head> <body> <script type="text/javascript"> // addition(加法) subtraction(减法) multiplicatio(乘法) division(除法) function addition(a,b){ var sum = a + b; return sum; } function subtraction(a,b){ return a - b; } function multiplicatio(a,b){ return a * b; } /* function division(a,b){ return a / b; } */ // 函数表达式 var division = function(a,b){ return a / b; } var r = addition(3,2); var r2 = subtraction(3,2); var r3= multiplicatio(3,2); var r4 = division(3,2); console.log(r); console.log(r2); console.log(r3); console.log(r4); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>函数作用域</title> </head> <body> <!-- <script type="text/javascript"> var a = 1; console.log(a); function add(){ var b = 3; console.log(a); } add(); // console.log(b); </script> --> <script type="text/javascript" src="js/first.js"></script> <script type="text/javascript" src="js/second.js"></script> <script type="text/javascript"> console.log(window); first(); second(); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>object</title> </head> <body> <script type="text/javascript"> /* var name = '火腿肠'; function 老虎(){ alert(name); } function 企鹅(){ alert(name); } 老虎(); */ // 对象 (属性和方法)字面量创建 姓名,年龄,性别 ,爱好(动作) var person = { name : 'mjj', age: 18, sex:'女', fav: function(a){ alert('爱好姑娘'); return '姑娘' + a + '岁'; } } console.log(person); console.log(person.name); console.log(person.fav(18)); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Javascript常用内置对象</title> </head> <body> <script type="text/javascript"> // 字面量创建一样 // var arr = [1,2,3]; // 内置对象 native object 对象 : 属性和方法 // document.write('呵呵呵'); // Array // js提供构造函数 var colors = new Array(); var colors2 = []; if (Array.isArray(colors)) { // 对数组进行操作 colors[0] = 'red'; colors[1] = 'blue'; colors[2] = 'yellow'; var a = colors.toString(); console.log(a); console.log(typeof a); console.log(colors); // console.log(colors[0]); // console.log(colors.length); }else{ // ..... } </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>数组常用的方法</title> </head> <body> <script type="text/javascript"> /* var arr = [1,2,3]; var a = arr.toString(); var b = arr.toLocaleString(); console.log(a); console.log(b); var person1 = { toLocaleString : function(){ return 'mjj'; }, toString: function(){ return '么吉吉'; } } var person2 = { toLocaleString : function(){ return '隔壁老王'; }, toString: function(){ return '隔壁老李'; } } var people = [person1,person2]; console.log(people); console.log(people.toString()); console.log(people.toLocaleString()); */ // 分割为字符串 var colors = ['red','blue','green']; var a = colors.join('|'); console.log(a); // red|blue|green // 栈(lifo last - in- first - out)方法. push() pop() 队列方法 // push() 往数组的最后一项添加内容 var newlength = colors.push('purple'); console.log(newlength); console.log(colors); // pop() 从数组末尾删除最后一项 var lastItem = colors.pop(); console.log(lastItem); console.log(colors); // 队列 fifo 先进先出 unshift() shift() newlength = colors.unshift('yellow'); console.log(newlength); console.log(colors); var firstItem = colors.shift(); console.log(firstItem); console.log(colors); var values = [0,3,2,16,15,10]; // 数组倒序 // values.reverse(); // console.log(values); // sort() 排序 升序 或者降序 // 对数据排序(示例) this.allData.sort((a, b) => { return a.value - b.value // 升序 }) // values.sort(); // console.log(values); //[0, 10, 15, 16, 2, 3] function compare1(a,b){ /* // a位于b之前 if (a < b ) { return -1; }else if(a > b){ return 1; }else{ return 0; } */ return a - b; } function compare2(a,b){ /* // a位于b之前 if (a < b ) { return 1; }else if(a > b){ return -1; }else{ return 0; } */ return b - a; } // values.sort(compare1); //升序 // console.log(values); values.sort(compare2); console.log(values); // 操作方法 concat() slice() splice() // 1.concat() 数组合并 var colors = ['red','blue']; var newColors = colors.concat('green'); newColors = newColors.concat({name:'zhangsan'}); console.log(newColors); //2.slice() 将当前数组中的一个或者多个项创建一个新数组 var newcolors = colors.concat({name:"lisi"},['black','purple']); console.log(newcolors); //5 // newcolors = newcolors.slice(1,2); newcolors = newcolors.slice(-1,-2); //slice(3,4) console.log(newcolors); // 3.splice() 删除 插入 替换 // 3.1 删除 var names = ['张三','李四','mjj','alex']; names.splice(0,2); console.log(names); // ["mjj", "alex"] // 3.2 插入 names.splice(1,0,'熊大大','jack'); console.log(names);// ["mjj", "熊大大", "jack", "alex"] // 3.3 替换 names.splice(1,1,'xiongdada'); console.log(names); // 第二个1代表插入的位置["mjj", "xiongdada", "jack", "alex"] // 4.位置方法 indexOf() lastIndexOf() var names = ['张三','mjj','王五','mjj','赵六']; // alert(names.indexOf('mjj')); //1 // alert(names.lastIndexOf('mjj')); //3 // alert(names.indexOf('mjj',2)); //3 // alert(names.lastIndexOf('mjj',2)); //1 // alert(names.lastIndexOf('mjjxxxx',2)); //如果查不到结果 返回-1 // 5.迭代方法 // 5.1 filter() 将数组的元素进行过滤 var numbers = [1,2,3,6,19,4,20]; var filterResult = numbers.filter(function(item,index,array){ console.log('item:'+ item); console.log('index:'+ index); console.log('array:'+ array); return item > 10 }); console.log(filterResult); // 5.2 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]); } // 5.3 forEach() mapresult.forEach(function(item,index){ console.log(item); }) </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>map方法的应用</title> </head> <body> <script type="text/javascript"> var oldArray = [ { name:'张三', age: 17 }, { name:'mjj', age: 29 }, { name:'李四', age: 30 } ]; /* var newNames = []; var newAges = []; for(var i = 0; i < oldArray.length; i ++){ var myname = oldArray[i].name; var myage = oldArray[i].age; newNames.push(myname); newAges.push(myage); } console.log(newNames); console.log(newAges); */ 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); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>字符串的常用方法</title> </head> <body> <script type="text/javascript"> // 属性 // length // 方法 /* charAt() charCodeAt() concat() slice() substring() substr() indexOf() lastIndexOf() trim() //常用 toLowerCase() toUpperCase() toLocaleLowerCase() toLocaleUpperCase() */ // var str = 'hello world'; //切片 /* console.log(str.length);//获取字符串的长度 11 console.log(str.charAt(1)); //e 获取指定的字符 console.log(str.charCodeAt(1)) //101 获取指定的字符对应的编码 console.log(str.concat(' mjj',' jack')); //拼接字符串 通常情况 不适用它来做拼接,使用 +来做多个字符的拼接 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,6)); console.log(str.slice(-3,-1)); //rld slice(8,10) console.log(str.slice(8,10)); */ var str = 'hello world'; console.log(str.indexOf('o')); //4 console.log(str.lastIndexOf('o')); //7 console.log(str.indexOf('o',6)); //7 console.log(str.lastIndexOf('o',6)); //4 // trim()清除当前 字符串的前后后格 var str = ' hello world '; console.log(str.trim()); console.log(str); var str = 'Hello Mjj'; // console.log(str.toUpperCase()); console.log(str.toLowerCase()); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 对“hello world”进行翻转处理 要求变为:"dlorw olleh" function reserve_str() { var alp = 'hello world' var r_alp = alp.split("") // console.log(r_alp) // ['d','l','r','o'..'e','h'] r_alp.reverse() //反转 var r_str = r_alp.join('') //拼接为字符串 return r_str } var s = reserve_str() alert(s) // 'dlrow olleh' </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>查找当前字符e在字符串中的所有位置</title> </head> <body> <script type="text/javascript"> // 查找e 在str中的所有的位置 var str = 'He unfolded the map and set it on the floor.'; var arr = []; var pos = str.indexOf('e'); //1 console.log(pos); while(pos > -1){ // 找到当前e字符对应的位置 arr.push(pos); pos = str.indexOf('e',pos+1); } console.log(arr); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Date日期对象</title> </head> <body> <script type="text/javascript"> // UTC 1970.1.1 到 285616年 // Date日期对象 /* 1.四种方式创建 var now = new Date(); console.log(now); var xmas = new Date('December 25,1995 13:30:00'); console.log(xmas); var xmas = new Date(1995,11,25); console.log(xmas); var xmas = new Date(1995,11,25,14,30,0); console.log(xmas); */ 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); // 日期格式化方法 console.log(now.toDateString()); //星期几 月 日 年 console.log(now.toTimeString()); //时 分 秒 时区 // 常用 console.log(now.toLocaleDateString()); // 2020/11/24 console.log(now.toLocaleTimeString()); //下午2:24:30 console.log(now.toLocaleString()); // 2020/11/24 下午2:24:30 console.log(now.toUTCString()); //Tue, 24 Nov 2020 06:24:30 GMT </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>返回用数字时钟格式的时间</title> </head> <body> <script type="text/javascript"> // 6:27:35 P.M. // 6:30:01 P.M. // 6:04:01 A.M. // :0 4 // : 30 function nowNumTime(){ var now = new Date(); var hour = now.getHours(); //0 ~ 23. //19 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); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>字符串和数值相互转换</title> </head> <body> <script type="text/javascript"> var str = '13131.9090013'; // 字符串转数值类型 console.log(parseInt(str)); console.log(parseFloat(str)); console.log(typeof parseFloat(str)); var a = Number(str); console.log(isNaN(a)); //NaN var num = 1313.179; // 强制类型转换 console.log(num.toString()); console.log(typeof num.toString()); console.log(String(num)); // 隐式转换 console.log('' + num); console.log(''.concat(num)); console.log(Number(num.toFixed(2))); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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 str='12333.12000256' //转换整型(字符串转换数值类型) console.log(parseInt(str)); console.log(parseFloat(str)); console.log(Number(str)); a =Number(str); console.log(isNaN(a)); //数值转换为字符串 var num =123.22 console.log(num.toString()); console.log(String(num)) //隐士转换 console.log(''+num); //获取指定小数位的的字符串 console.log(num.toFixed(1)); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Globle对象</title> </head> <body> <script type="text/javascript"> // URI var uri = 'http://www.apeland.cn/web index.html?name=zhangsan'; // encodeURIComponent()编码 使用最多的方法 console.log(encodeURI(uri));//只能解析空格 console.log(encodeURIComponent(uri)); //使用做多 // 解码 decodeURIComponent() // decodeURI(encodeuri); // decodeURIComponent(encodeuri); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>window对象</title> </head> <body> <script type="text/javascript"> var a = 3; console.log(window.a); function hello(){ alert(window.a); } window.hello(); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Math对象</title> </head> <body> <script type="text/javascript"> // Math // var a = 3; // 方法 min() max() var max = Math.max(3,34,56,21); var min = Math.min(3,34,56,21); var arr = [1,2,32,23,45,21]; var max = Math.max.apply(null,arr); var min = Math.min.apply(null,arr); // var max= Math.max(arr[0],arr[1],arr[2]); console.log(max); console.log(min); // ceil() floor() round() var num = 24.8; console.log(Math.ceil(num)); //天花板函数 向上取整 console.log(Math.floor(num)); //地板函数 向下取整 console.log(Math.round(num)); //标准的四舍五入 // 随机数 random() 0 <= random<1 console.log(Math.random()); // 1.获取min到max之间的整数 // 2.获取随机颜色 rgb(0~255,0~255,0~255); // 3.随机验证码 四位 数字+ 字母 (大写) </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>练习</title> </head> <body> <script type="text/javascript"> // 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 result 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; // 3.随机验证码 四位 数字+ 字母 (大写) 65Yz function creatCode(){ // 设置默认的空的字符串 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); code += randomCode[index]; } return code; } var rndcode = creatCode(); console.log(rndcode); document.write(`<h1>${rndcode}</h1`) </script> </body> </html>
33 异常处理
try { //这段代码从上往下运行,其中任何一个语句抛出异常该代码块就结束运行 var name = '' } catch (e) { // 如果try代码块中抛出了异常,catch代码块中的代码就会被执行。 //e是一个局部变量,用来指向Error对象或者其他抛出的对象 } finally { //无论try中代码是否有异常抛出(甚至是try代码块中有return语句),finally代码块中始终会被执行。 }