JavaScript中常用的方法汇总,全部整理好了,一定要收藏!

Array
new Set()
const arr = [3,4,4,5,4,6,5,7];console.log(new Set(arr)); // {3,4,5,6,7}const a = Array.from(new Set(arr)) // [3, 4, 5, 6, 7]
sort()
const arr = [3,4,4,5,4,6,5,7];console.log(arr.sort()) // [3, 4, 4, 4, 5, 5, 6, 7]
reverse()
const arr = [3,4,4,5,4,6,5,7];conosle.log(arr.reverse()); // [7, 6, 5, 5, 4, 4, 4, 3]
delete
//数组const arr = [3,4,4,5,4,6,5,7];delete arr[1];conosle.log(arr); // [3, empty, 4, 5, 4, 6, 5, 7]//对象const obj = {name: 'pboebe',age: '23',sex: '女'};delete obj.sex;console.log(obj); // {name: "pboebe", age: "23"}
shift()
const arr = [3,4,4,5,4,6,5,7];const a = arr.shift(); // 3console.log(arr); // [empty, 4, 5, 4, 6, 5, 7]
unshift()
const arr = [3,4,4,5,4,6,5,7];const a = arr.unshift(8);console.log(a); // 9(a为返回的数组的新长度)console.log(arr); // [8, 3, 4, 4, 5, 4, 6, 5, 7]
push()
const arr = [3,4,4,5,4,6,5,7];const a = arr.push(8,9);console.log(a); // 10(a为返回的数组的新长度)console.log(arr); // [3, 4, 4, 5, 4, 6, 5, 7, 8, 9]
valueOf()
const arr = [3,4,4,5,4,6,5,7];console.log(arr.valueOf()); // [3,4,4,5,4,6,5,7]
toString()
const arr = [3,4,4,5,4,6,5,7];console.log(arr.toString()); // 3,4,4,5,4,6,5,7
concat()
//数组const a = [1,2,3];const b = [4,5];const c = a.concat(b); // [1, 2, 3, 4, 5]//字符串const x = 'abc';const y = 'def';const z = x.concat(y); // abcdef
join()
const arr = [3,4,4,5,4,6,5,7];console.log(arr.join('-')); // 3-4-4-5-4-6-5-7
slice(start, end)
//数组const arr = [3,4,4,5,4,6,5,7];const a = arr.slice(2, 5); // [4, 5, 4]//字符串const x = 'abcdefgh';const y = x.slice(3, 6); // def
splice()
const arr = [3,4,4,5,4,6,5,7];const a = arr.splice(3, 2, 12); // [5, 4]console.log(arr); // [3, 4, 4, 12, 6, 5, 7]
map()
const arr = [3,4,4,5,4,6,5,7];const a = arr.map(item => item*2;) // [6, 8, 8, 10, 8, 12, 10, 14]
forEach()
const arr = [3,4,4,5,4,6,5,7];arr.forEach(function(value,index,arr){console.log(value)}))
for in()
// 对象const obj = {a: 123, b: 12, c: 2 };for (let a in obj) {console.log(a)}// abc//数组const arr = [3,4,4,5];for(let a in arr) {console.log(a)}// 0123
filter()
const arr = [3,4,4,5,4,6,5,7];const a = arr.filter(item => item % 3 > 1);console.log(a); // [5, 5]
some()& every()
const arr = [3,4,4,5,4,6,5,7];console.log( arr.some( function( item, index, array ){console.log( 'item=' + item + ',index='+index+',array='+array );return item > 3;}));// item=3,index=0,array=3,4,4,5,4,6,5,7// item=4,index=1,array=3,4,4,5,4,6,5,7// trueconsole.log( arr.every( function( item, index, array ){console.log( 'item=' + item + ',index='+index+',array='+array );return item > 3;}));// item=3,index=0,array=3,4,4,5,4,6,5,7//false
every方法是需要每一个返回值为true,才能返回true,否则为false;
reduce()
reduce(a, b, x, y)
//简单用法const arr = [3,4,4,5,4,6,5,7];const a = arr.reduce((pre, cur) => {return pre+cur})// 逗号写法const a = arr.reduce((pre, cur) => (sum= pre+cur, sum))console.log(a) // 38//高级用法(举个数组去重和数组扁平化栗子)const b = arr.reduce((pre, cur) => {if(!pre.includes(cur)) {return pre.concat(cur)} else {return pre}}, [])// [3, 4, 5, 6, 7]const arrs = [[2,3,2], [3,4,5]]const c = arr.reduce((pre, cur) => {return pre.concat(cur)}, [])// [2, 3, 2, 3, 4, 5]
reduceRight()
indexOf()
//数组const arr = [3,4,4,5,4,6,5,7];console.log(arr.indexOf(4)) // 1console.log(arr.indexOf('4')) // -1//字符串conststring = 'asdfghj';console.log(string.indexOf('a')) // 0
lastIndexOf()
const arr = [3,4,4,5,4,6,5,7];console.log(arr.lastIndexOf(4))// 4(从左到右数最后出现的位置,字符串同理)
groupBy()
const arr = [{name: '小孙', age: 18, score: 60, weight: 60},{name: '小王', age: 19, score: 70, weight: 55},{name: '小李', age: 18, score: 60, weight: 70},{name: '小刘', age: 20, score: 70, weight: 65},{name: '小赵', age: 18, score: 60, weight: 60},{name: '小钱', age: 19, score: 70, weight: 55},{name: '小周', age: 20, score: 60, weight: 50},];const example = (data, key) => {return data.reduce(function(prev, cur) {(prev[cur[key]] = prev[cur[key]] || []).push(cur);return prev;}, {});};console.log(example(arr, 'age'));// object: {18: Array(3), 19: Array(2), 20: Array(2)}18: Array(3)0: {name: "小孙", age: 18, score: 60, weight: 60}1: {name: "小李", age: 18, score: 60, weight: 70}2: {name: "小赵", age: 18, score: 60, weight: 60}19: Array(2)0: {name: "小王", age: 19, score: 70, weight: 55}1: {name: "小钱", age: 19, score: 70, weight: 55}20: Array(2)0: {name: "小刘", age: 20, score: 70, weight: 65}1: {name: "小周", age: 20, score: 60, weight: 50}
shuffle()
const arr = [1,2,3,4,5,6,7,8,9,10];const shuffle = ([...arr]) => {let m = arr.length;while (m) {const i = Math.floor(Math.random() * m--);[arr[m], arr[i]] = [arr[i], arr[m]];}return arr;};console.log(shuffle(arr))// [10, 9, 7, 5, 6, 4, 1, 2, 8, 3]
flatten()
const arr = [[1,2,3],[4,5,[6,7]]];const a = arr.flatten(3);console.log(a); // [1, 2, 3, 4, 5, 6, 7]
Array.isArray()
const arr = [3,4,4,5,4,6,5,7];console.log(Array.isArray(arr)) // true
copyWithin()
格式:array.copyWithin(target, start, end)const arr = [3,4,4,5,4,6,5,7];console.log(arr.copyWithin(4,2)) // [3, 4, 4, 5, 4, 5, 4, 6]
find()
const arr = [3,4,4,5,4,6,5,7];const a = test.find(item => item > 3);console.log(a); //4(find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。)const b = test.find(item => item == 0);console.log(b); //undefined(如果没有符合条件的元素返回 undefined)
String
charAt()
const str = 'hello guys';console.log(str.charAt(3)) // l
charCodeAt()
const str = 'hello guys';console.log(str.charCodeAt(3)) // 111
match()
const str = 'hello guys';console.log(str.match('guys')) // ["guys"]// 使用正则匹配字符串const strs = '1.hello guys, 2.are you ok?';console.log(strs.match(/\d+/g)) // ["1", "2"]
replace()
const str = 'hello guys';console.log(str.replace('guys', 'man')) // hello man
search()
const str = 'hello guys';console.log(str.search('guys')) // 6console.log(str.indexOf('guys')) // 6// 区别conststring = 'abcdefg.1234';console.log(string.search(/\./)) // 7(转译之后可以匹配到 . 的位置)console.log(string.indexOf(/\./)) // -1 (相当于匹配/\./,找不到则返回-1,只能匹配字符串)
split()
const str = 'hello guys';console.log(str.split('')) // ["h", "e", "l", "l", "o", " ", "g", "u", "y", "s"]console.log(str.split('', 3)) // ["h", "e", "l"]
toLocaleLowerCase()& toLowerCase()
const str = 'hello guys';console.log(str.toLocaleLowerCase()) // hello guysconsole.log(str.toLowerCase()) // hello guys
toLocaleUpperCase() & toUpperCase()
const str = 'hello guys';console.log(str.toLocaleUpperCase()) // HELLO GUYSconsole.log(str.toUpperCase()) // HELLO GUYS
substr()
const str = 'hello guys';console.log(str.substr(2)) // llo guysconsole.log(str.substr(2, 7)) // llo guy
substring()
const str = 'hello guys';console.log(str.substring(2)) // llo guysconsole.log(str.substring(2, 7)) // llo g
.trim()
const str = ' hello guys ';console.log(str.trim()) // hello guys(不会改变原数组)
常用的http:// json.xxx 方法
JSON.parse()
const str = '{"name": "phoebe", "age": 20}';const obj = JSON.parse(str) // {name: "phoebe", age: 20}(object类型)
JSON.stringify()
const obj = {"name": "Tins", "age": 22};const str = JSON.stringify(obj) // {"name":"Tins","age":22}(string类型)
Object 实例对象的方法主要有以下六个
Object.Prototype.valueOf()
ObjectrType.prototype.valueOf = function() { return customValue; };
ObjectrType.valueOf()
Object.Prototype.toString()
functionDog(name) {this.name = name;}const dog1 = new Dog('Gabby');Dog.prototype.toString = functiondogToString() {return'' + this.name;}console.log(dog1.toString()); // Gabby
Object.Prototype.toLocaleString()
let foo = {};foo.toLocaleString(); // "[object Object]"
Object.Prototype.isPrototypeOf()
Object.prototype.isPrototypeOf(targetObj)const arr = [];Array.prototype.isPrototypeOf(arr); // true// 修改obj的原型Object.setPrototypeOf(arr, String.prototype);Array.prototype.isPrototypeOf(arr); // falseString.prototype.isPrototypeOf(arr); // true
Object.Prototype.hasOwnProperty()
let obj = {};// 定义一个object实例obj.prop1 = 'value1'; // prop1是一个自有属性obj.constructor.prototype.prop2 = 'value2'; // prop2是一个原型链属性// 无论自有属性还是原型链属性,我们都可以访问到console.info(obj.prop1); // value1console.info(obj.prop2); // value2// 使用`hasOwnProperty()`方法判断属性是否为自有属性obj.hasOwnProperty('prop1'); // trueobj.hasOwnProperty('prop2'); // false
Object.Prototype.PropertyIsEnumerable()
const obj = { name: 'ecmaer'};Object.getOwnPropertyDescriptor(obj, 'name').enumerable; // trueobj.propertyIsEnumerable('name'); // true// 将属性name设置成不可枚举Object.defineProperty(obj, 'name', {enumerable: false});obj.propertyIsEnumerable('name'); // falsefor(let i in obj){console.info(obj[i]); // 没有遍历出'ecmaer'}
Javascript的三种判断一个值的类型的办法
typeOf()
typeof 123 //numbertypeof '123' //stringtypeof true // booleantypeof false //booleantypeof undefined // undefinedtypeof Math.abs // functiontypeof function () {} // function// 当遇上`null`、`Array`和通常意义上的`object`,都会返回 objecttypeof null // objecttypeof [] // object(所以判断数组时可以使用Array.isArray(arr))typeof {} // object// 当数据使用了new关键字和包装对象以后,数据都会变成Object类型,不加new关键字时会被当作普通的函数处理。typeof new Number(123); //'object'typeof Number(123); // 'number'typeof new Boolean(true); //'object'typeof Boolean(true); // 'boolean'typeof new String(123); // 'object'typeof String(123); // 'string'
instanceOf()
function Car(make, model, year) {this.make = make;this.model = model;this.year = year;}const auto = new Car('Honda', 'Accord', 1998);console.log(auto instanceof Car); // trueconsole.log(auto instanceof Object); // true
Object.Prototype.toString()(推荐)
const arrs = [1,2,3];console.log(typeof arrs) // objectconsole.log(Object.Prototype.toString.call(arrs)) // [object Array]
call,apply以及bind的用法,区别及相似住处
用法
const arr = [2,5,4,7,6]const a = Function.prototype.apply.call(Math.max, null,arr)console.log(a) // 7
const arr = [2,5,4,7,6]const a = Function.prototype.call.apply(Math.max, arr)console.log(a) // 7//如果apply的第二个参数是个null,会返回-Infinityconst b = Function.prototype.call.apply(Math.max, null, arr)console.log(b) // -Infinity
const fruits = {"name": "apple",getOtherFriut: function() {return this.name;}}const color = {"name": " is red"}const fruitColor = fruits.getOtherFriut.bind(this, color)console.log(fruitColor()) //is redconst arr = [2,5,4,7,6]const a = Function.prototype.call.apply(Math.max, arr)console.log(a) // 7//如果apply的第二个参数是个null,会返回-Infinityconst b = Function.prototype.call.apply(Math.max, null, arr)console.log(b) // -Infinity
相似之处
都是用来改变函数的
this对象;第一个参数都是
this要指向的对象;都可利用后继参数传参;
区别
都可以用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由
thisObj指定的新对象。bind()是返回一个新函数,供以后调用,而apply()和call()是立即调用。call()和apply()唯一区别是参数不一样,call()是apply()的语法糖;
选择使用
如果不需要关心具体有多少参数被传入函数,选用
apply();如果确定函数可接收多少个参数,并且想一目了然表达形参和实参的对应关系,用
call();如果想要将来再调用方法,不需立即得到函数返回结果,则使用
bind();
Date对象的用法
const date = new Date();
Date(): 返回当日的日期和时间;
getDate(): 从Date对象返回一个月中的某一天(1~31)console.log(date.getDate());
getDay():从Date对象返回一周中的某一天(0~6);
getMonth(): 从Date对象返回月份(0~11);
getFullYear(): 从Date对象以四位数字返回年份;
getYear():可以使用getFullYear()代替;
getHours(): 返回Date()对象的小时(0~23);
getMinutes(): 返回Date()对象的分钟(0~59);
getSeconds(): 返回Date()对象的分钟(0~59);
getMillseconds(): 返回Date()对象的毫秒(0~999);
getTime(): 返回1970年1月1日至今的时间;
getTimezoneOffset(): 返回本地时间与格林威治标准时间(GMT)的分钟差;
getUTCDate(): 根据世界时从Date对象返回月中的一天(1~31);
getUTCDay(): 根据世界时从Date对象返回周中的一天(1~6);
getUTCMonth(): 根据世界时从Date对象返回月份(0~11);
getUTCFullYear(): 根据世界时从Date对象返回四位数的年份;
getUTCHours(): 根据世界时从Date对象返回对象的小时(0~23);
getUTCMinutes(): 根据世界时从Date对象返回对象的分钟(0~59);
getUTCSeconds(): 根据世界时从Date对象返回对象的秒钟(0~59);
getUTCMillseconds(): 根据世界时从Date对象返回对象的毫秒(0~999);
parse(): 返回1970年1月1日午夜到指定日期(字符串)的毫秒数;
setDate(): 设置Date对象中月的某一天(1~31);
setMonth(): 设置Date对象中月份(0~11);
setFullYear(): 设置Date对象中的年份(四位数字);
Math.xx开头的方法
Math.ceil(): 对数进行上舍入(天花板函数) 大于等于 x,并且与它最接近的整数。
Math.floor(): 对数进行下舍入(地板函数)。
Math.max(x,y):返回x,y中的最大值。
Math.min(x,y):返回x,y中的最小值。
Math.pow(x,y): 返回x的y次方。
Math.random() : 返回0-1之间的随机数。
Math.round(x): 四舍五入。
Math.abs(x):返回数的绝对值。
Math.acos(x):返回数的反余弦值。
Math.asin(x): 返回数的反正弦值。
Math.atan(x):返回数的反正切值。
Math.atan2(y,x):返回由x轴到点(x,y)的角度(以弧度为单位)。
Math.cos(x): 返回数的余弦值。
Math.exp(e): 返回e的指数。
Math.log(x):返回数的自然对数(以e为底数)。
Math.sin(x):返回数的正弦值。
Math.sqrt(x):返回数的平方根。
Math.tan(x): 返回角的正切值。
Math.toSource():返回该对象的源代码。
Math.valueOf(): 返回Math对象的原始值。
简单的数组去重
最便捷的方法:[...new Set(arr)]
const arr = [4,5,3,4,6,5,8,6];console.log(Array.from(new Set(arr))) // [4, 5, 3, 6, 8]console.log([...new Set(arr)]) // [4, 5, 3, 6, 8]
const arr = [4,5,3,4,6,5,8,6];const a = arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]);console.log(a) // [4, 5, 3, 6, 8]
const arr = [4,5,3,4,6,5,8,6];const b = arr.filter((item, index, arr) => arr.indexOf(item, 0) === index;) // [4, 5, 3, 6, 8]
const arr = [4,5,3,4,6,5,8,6];function duplicate (arr) {var obj = {};return arr.filter(function(item, index, arr){return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)})}console.log(duplicate(arr)) // 4, 5, 3, 6, 8]
结语

