构造函数html
// 建立对象 var person = new Object(); // 给对象添加name和age属性 person.name = 'jack'; person.age = 28; // 给对象添加fav的方法 person.fav = function(){ console.log('泡妹子'); } // 特殊: var person = {}; // 与new Object()相同
使用对象字面量表示法前端
var person = { name : 'jack'; age : 28, fav : function(){ console.log('泡妹子'); } }
var obj = {}; obj.name = 'mjj'; obj.fav = function(){ console.log(this); // 此时this指向当前对象,即obj } console.log(this); // 此时this指向window function add(x,y) { console.log(this.name); } add(); // 空值,此时this指向window add.call(obj,1,2); // 此时this指向传入的对象,即obj add.apply(obj,[1,2]); // 此时this指向传入的对象,即obj (function () { console.log(this); // 此时this指向window })()
访问对象中属性的方法es6
person.name; // jack person.fav(); // 泡妹子
person['name']; // 至关于person.name;
遍历对象数组
var obj = {}; for (var key in obj){ obj[key] }
面向对象app
// 使用构造函数来建立对象 function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return '(' + this.x + ', ' + this.y + ')'; }; var p = new Point(1, 2); // es6用class来建立对象 class Person{ constructor(name,age){ // 初始化 this.name = name; this.age = age; } fav(){ console.log(this.name); } } var p = new Person('mjj',18); p.fav();
数组的建立方式dom
var colors = new Array();
var colors = [];
Array.isArray():肯定某个值究竟是否是数组函数
var colors = ['red','green','blue']; Array.isArray(colors); // true
toString():返回由数组中每一个值以一个以逗号拼接成的字符串this
var colors = ['red','green','blue']; alert(colors.toString()); // red,green,blue
join方法:返回由数组中每一个值以相同符号拼接成的字符串编码
var colors = ['red','blue','green']; colors.join('||'); // red||blue||green
栈方法:LIFO(后进先出)prototype
var colors = []; var count = colors.push('red','blue','green'); alert(count); // 3
var item = colors.pop(); // 取最后一项 alert(item); // green alert(colors.length); // 2
队列方法:FIFO(先进先出)
var colors = []; var count = colors.unshift('red','green'); // 推入两项 alert(count); // 2 console.log(colors); // ["red", "green"]
var colors = ['red','blue','green']; var item = colors.shift(); // 取得第一项 alert(item); // "red" alert(colors.length); // 2
重排序方法
var values = [1,2,3,4,5]; values.reverse(); alert(values); // 5,4,3,2,1
// 升序 function compare(v1,v2){ if(v1 < v2){ return -1; }else if (v1 > v2){ return 1; }else{ return 0; } } var values = [0,1,5,10,15]; values.sort(compare); alert(values); // 0,1,5,10,15 // 降序 function compare(v1,v2){ if(v1 < v2){ return 1; }else if (v1 > v2){ return -1; }else{ return 0; } } var values = [0, 1, 5, 10, 15]; values.sort(compare); alert(values); // 15,10,5,1,0
操做方法
var colors = ['red','blue','green']; colors.concat('yello'); // ["red", "blue", "green", "yello"] colors.concat({'name':'张三'}); // ["red", "blue", "green", {…}] colors.concat({'name':'李四'},['black','brown']); // ["red", "blue", "green", {…}, "black", "brown"]
var colors = ['red','blue','green','yellow','purple']; // 正值状况下 colors.slice(1); // ["blue", "green", "yellow", "purple"] colors.slice(1,4); // ["blue", "green", "yellow"] // 负值状况下 colors.slice(-2,-1); // ["yellow"] colors.slice(-1,-2); // []
var colors = ["red", "green", "blue"]; var removed = colors.splice(0,1); alert(colors); // green,blue alert(removed); // red,返回的数组中只包含一项 removed = colors.splice(1, 0, "yellow", "orange"); alert(colors); // green,yellow,orange,blue alert(removed); // 返回的是一个空数组 removed = colors.splice(1, 1, "red", "purple"); alert(colors); // green,red,purple,orange,blue alert(removed); // yellow,返回的数组中只包含一项
位置方法
var numbers = [1,2,3,4,5,4,3,2,1]; numbers.indexOf(4); // 3 numbers.lastIndexOf(4); // 5 numbers.indexOf(4,4); // 5 numbers.lastIndexOf(4,4); // 3 var person = {name:"mjj"}; var people = [{name:'mjj'}]; var morePeople = [person]; people.indexOf(person); // -1 morePeople.indexOf(person); // 0
迭代方法
var numbers = [1,2,3,4,5,4,3,2,1]; var filterResult = numbers.filter(function(item, index, array){ return (item > 2); }); alert(filterResult); // [3,4,5,4,3]
var numbers = [1,2,3,4,5,4,3,2,1]; var filterResult = numbers.map(function(item, index, array){ return item * 2; }); alert(filterResult); // [2,4,6,8,10,8,6,4,2]
//执行某些操做,至关于for循环 var numbers = [1,2,3,4,5,4,3,2,1]; numbers.forEach(function(item, index, array){ });
字符串的建立方式
var stringValue = "hello world";
length属性
var stringValue = "hello world"; alert(stringValue.length); // "11"
字符方法
var stringValue = "hello world"; alert(stringValue.charAt(1)); // "e"
var stringValue = "hello world"; alert(stringValue.charCodeAt(1)); // 输出"101"
字符操做方法
var stringValue = "hello "; var result = stringValue.concat("world"); alert(result); // "hello world" alert(stringValue); // "hello" // concat()方法能够接受任意多个参数,也就是说能够经过它来拼接任意多个字符串 var stringValue = "hello "; var result = stringValue.concat("world", "!"); alert(result); // "hello world!" // 拼接字符串 // 通用方式: var name = 'wusir', age = 28; var str = name + '今年是' + age + '岁了,快要结婚了,娶了个黑姑娘'; // es6的模板字符串,使用``(Tab上面的那个键) var str2 = `${name}今年是${age}岁了,快要结婚了,娶了个黑姑娘`;
var stringValue = "hello world"; // 正值状况下 stringValue.slice(3); // "lo world" stringValue.substring(3); // "lo world" stringValue.substr(3)); // "lo world" stringValue.slice(3, 7); // "lo w" stringValue.substring(3,7); // "lo w" stringValue.substr(3, 7); // "lo worl // 负值状况下 stringValue.slice(-3); // "rld" stringValue.substring(-3); // "hello world" stringValue.substr(-3); // "rld" stringValue.slice(3, -4); // "lo w" stringValue.substring(3, -4); // "hel" stringValue.substr(3, -4); // ""(空字符串)
字符串位置方法
var stringValue = "hello world"; alert(stringValue.indexOf("o")); // 4 alert(stringValue.lastIndexOf("o")); // 7 alert(stringValue.indexOf("o", 6)); // 7 alert(stringValue.lastIndexOf("o", 6)); // 4
trim():删除字符串的先后空格
var stringValue = " hello world "; stringValue.trim(); // "hello world"
字符串大小写转换方法
var stringValue = "hello world"; stringValue.toUpperCase(); // "HELLO WORLD" stringValue.toLowerCase(); // "hello world"
日期对象的建立方式
var myDate = new Date();
基本方法
日期格式化方法
var myDate = new Date(); myDate.toLocaleString(); // "2019/6/4 上午9:33:58" myDate.toDateString(); // "Mon Apr 15 2019" myDate.toTimeString(); // "10:11:53 GMT+0800 (中国标准时间)" myDate.toUTCString(); // "Mon, 15 Apr 2019 02:11:53 GMT"
将今天的星期数显示在网页上,即写入body中,使用document.write
var weeks = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六']; console.log(weeks[date.getDay()]); var day = weeks[date.getDay()]; document.write(`<a href="#">${day}</a>`);
数字时钟
var time = new Date(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var temp = "" + ((hour > 12) ? hour - 12 : hour); if (hour == 0) temp = "12"; temp += ((minute < 10) ? ":0" : ":") + minute; temp += ((second < 10) ? ":0" : ":") + second; temp += (hour >= 12) ? " P.M." : " A.M."; alert(temp);
<body> <h2 id="time"></h2> <script> var timeObj = document.getElementById('time'); console.log(time); function getNowTime() { var time = new Date(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var temp = "" + ((hour > 12) ? hour - 12 : hour); if (hour == 0) { temp = "12"; } temp += ((minute < 10) ? ":0" : ":") + minute; temp += ((second < 10) ? ":0" : ":") + second; temp += (hour >= 12) ? " P.M." : " A.M."; timeObj.innerText = temp; } setInterval(getNowTime, 20) </script> </body>
min()和max()方法
var max = Math.max(3, 54, 32, 16); alert(max); // 54 var min = Math.min(3, 54, 32, 16); alert(min); // 3 // 特殊:使用apply,找到数组中最大或最小值 var values = [1,2,36,23,43,3,41]; var max = Math.max.apply(null, values);
舍入方法
var num = 25.7; var num2 = 25.2; Math.ceil(num); // 26 Math.floor(num); // 25 Math.round(num); // 26 Math.round(num2); // 25
random()方法
// 例1:获取min到max的范围的整数 function random(lower, upper) { return Math.floor(Math.random() * (upper - lower)) + lower; } // 例2: 获取随机颜色 /* 产生一个随机的rgb颜色 @return {String} 返回颜色rgb值字符串内容,如:rgb(201, 57, 96) */ function randomColor() { // 随机生成rgb值,每一个颜色值在0-255之间 var r = random(0, 256), g = random(0, 256), b = random(0, 256); // 链接字符串的结果 var result = "rgb("+ r +","+ g +","+ b +")"; // 返回结果 return result; } // 例3: 获取随机验证码 function createCode(){ //首先默认code为空字符串 var code = ''; //设置长度,这里看需求,我这里设置了4 var codeLength = 4; //设置随机字符 var random = [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']; //循环codeLength 我设置的4就是循环4次 for(var i = 0; i < codeLength; i++){ //设置随机数范围,这设置为0 ~ 36 var index = Math.floor(Math.random()*36); //字符串拼接 将每次随机的字符 进行拼接 code += random[index]; } //将拼接好的字符串赋值给展现的Value return code }
字符串转数值
var str = '123.0000111'; console.log(parseInt(str)); // 123 console.log(typeof parseInt(str)); // number console.log(parseFloat(str)); // 123.0000111 console.log(typeof parseFloat(str)); // number console.log(Number(str)); // 123.0000111
数值转字符串
var num = 1233.006; // 强制类型转换 console.log(String(num)); console.log(num.toString()); // 隐式转换 console.log(''.concat(num)); // toFixed()方法会按照指定的小数位返回数值的字符串 四舍五入 console.log(num.toFixed(2));