不知不觉上班一周辽~趁着大好周末,小编挣扎着从床上爬起来,决定对前端平常编程中经常使用到的一些方法作一个系统的整合。前端
有些人或许会以为忘了百度就完事儿,no no no!这事儿小编真的亲践过好屡次,百度一次记住了还好,记不住下次碰着了还得找度娘简直是拉低工做效率。正则表达式
本次整理但愿能够帮助到须要的童鞋,闲暇无聊多瞅几眼保证能记住(记不住欢迎下方戳小编,小编必定给各位大佬寄“拖鞋”)。由于js这类的方法(技巧)总有新玩法,本篇文档会持续更新,建议收藏。算法
用来对数组进行去重。编程
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]
复制代码
对数组元素进行排序(改变原数组)。数组
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.sort()) // [3, 4, 4, 4, 5, 5, 6, 7]
复制代码
反转数组中的元素(改变原数组)。bash
const arr = [3,4,4,5,4,6,5,7];
conosle.log(arr.reverse()); // [7, 6, 5, 5, 4, 4, 4, 3]
复制代码
删除一个数组成员,会造成空位,并不会影响length属性(改变原数组),一样适用于对象。数据结构
//数组
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"}
复制代码
把数组的第一个元素从其中删除,并返回第一个元素的值(改变原数组)。app
const arr = [3,4,4,5,4,6,5,7];
const a = arr.shift(); // 3
console.log(arr); // [empty, 4, 5, 4, 6, 5, 7]
复制代码
向数组的起始处添加一个或多个元素,并返回新的长度(改变原数组)。dom
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]
复制代码
在数组的末端添加一个或多个元素,并返回添加新元素后的数组长度(改变原数组)。函数
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]
复制代码
返回数组自己。
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.valueOf()); // [3,4,4,5,4,6,5,7]
复制代码
可把值转换成字符串。
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.toString()); // 3,4,4,5,4,6,5,7
复制代码
在原始数据尾部添加另外数据组成新数据(字符串适用)。
//数组
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
复制代码
以参数做为分隔符,将全部参数组成一个字符串返回(通常默认逗号隔开)。
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.join('-')); // 3-4-4-5-4-6-5-7
复制代码
用于提取原来数组的一部分,会返回一个提取的新数组,原数组不变(字符串适用,不包括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(t, v, s)t:被删除元素的起始位置;v:被删除元素个数;s:s以及后面的元素为被插入的新元素。
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方法一样适用于字符串,可是不能直接调用,须要经过函数的call方法,间接使用,或者先将字符串川转为数组,再使用)(不会改变原始数组)。
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]
复制代码
跟map方法相似,遍历数组,区别是无返回值。
const arr = [3,4,4,5,4,6,5,7];
arr.forEach(function(value,index,arr){console.log(value)}))
//3
4
4
5
4
6
5
7
复制代码
跟map
方法相似,遍历对象或者数组。
但值得注意的是for in
循环返回的值都是数据结构的键值名
。 遍历对象返回的对象的key值,遍历数组返回的数组的下标(key)。
// 对象
const obj = {a: 123, b: 12, c: 2 };
for (let a in obj) {
console.log(a)
}
// a
b
c
//数组
const arr = [3,4,4,5];
for(let a in arr) {
console.log(a)
}
// 0
1
2
3
复制代码
一个过滤方法,参数是一个函数,全部的数组成员依次执行该函数,返回结果为true
的成员组成一个新数组返回。(不会改变原始数组)。
const arr = [3,4,4,5,4,6,5,7];
const a = arr.filter(item => item % 3 > 1);
console.log(a); // [5, 5]
复制代码
这两个方法相似于“断言”(assert
),用来判断数组成员是否符合某种条件。
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
// true
console.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
复制代码
依次处理数组的每一个成员,最终累计成一个值。
格式:
reduce(a, b, x, y)
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]
复制代码
reduce
的用法还有不少,剋各类尝试。
与reduce
方法使用方式相同,区别在于reduceRight
方法从右到左执行(例子略过)。
返回给定元素在数组中的第一次出现的位置,若是没有则返回-1(一样适用于字符串)。
//数组
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.indexOf(4)) // 1
console.log(arr.indexOf('4')) // -1
//字符串
const string = 'asdfghj';
console.log(string.indexOf('a')) // 0
复制代码
返回给定元素在数组中最后一次出现的位置,没有返回-1(一样适用于字符串)。
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.lastIndexOf(4))
// 4(从左到右数最后出现的位置,字符串同理)
复制代码
把集合的元素按照key归类,key由传入的参数返回。
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}
复制代码
用洗牌算法随机打乱一个集合。
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]
复制代码
简写为flat(),接收一个数组,不管这个数组里嵌套了多少个数组,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]
复制代码
用来判断是否是数据是否是一个数组,返回值为true或false。
const arr = [3,4,4,5,4,6,5,7];
console.log(Array.isArray(arr)) // true
复制代码
从数组的指定位置拷贝元素到数组的另外一个指定位置中。
格式: 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]
复制代码
返回符合传入测试(函数)条件的数组元素。
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)
复制代码
用于返回指定位置的字符。
const str = 'hello guys';
console.log(str.charAt(3)) // l
复制代码
用于返回指定位置的字符的Unicode编码。
const str = 'hello guys';
console.log(str.charCodeAt(3)) // 111
复制代码
用于在字符串内检索指定的值或找到一个或多个正则表达式的匹配,返回的是值而不是值的位置。
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"]
复制代码
替换匹配的字符串。
const str = 'hello guys';
console.log(str.replace('guys', 'man')) // hello man
复制代码
用于检索与字符串匹配的子串,返回的是地址,与indexOf()
的区别是 search
是强制正则的,而 indexOf
只是按字符串匹配的。
const str = 'hello guys';
console.log(str.search('guys')) // 6
console.log(str.indexOf('guys')) // 6
// 区别
const string = 'abcdefg.1234';
console.log(string.search(/\./)) // 7(转译以后能够匹配到 . 的位置)
console.log(string.indexOf(/\./)) // -1 (至关于匹配/\./,找不到则返回-1,只能匹配字符串)
复制代码
将字符串切割成数组。
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"]
复制代码
将字符串转换成小写。
const str = 'hello guys';
console.log(str.toLocaleLowerCase()) // hello guys
console.log(str.toLowerCase()) // hello guys
复制代码
将字符串转换成大写。
const str = 'hello guys';
console.log(str.toLocaleUpperCase()) // HELLO GUYS
console.log(str.toUpperCase()) // HELLO GUYS
复制代码
用于从起始索引号提取字符串中指定数目的字符。
const str = 'hello guys';
console.log(str.substr(2)) // llo guys
console.log(str.substr(2, 7)) // llo guy
复制代码
用于提取字符串中两个指定索引号之间的字符。(与 slice()
和 substr()
方法不一样的是,substring()
不接受负的参数。)
const str = 'hello guys';
console.log(str.substring(2)) // llo guys
console.log(str.substring(2, 7)) // llo g
复制代码
去掉字符串两端的空格。
const str = ' hello guys ';
console.log(str.trim()) // hello guys(不会改变原数组)
复制代码
用于把字符串转化为对象。
const str = '{"name": "phoebe", "age": 20}';
const obj = JSON.parse(str) // {name: "phoebe", age: 20}(object类型)
复制代码
用于把对象转化为字符串。
const obj = {"name": "Tins", "age": 22};
const str = JSON.stringify(obj) // {"name":"Tins","age":22}(string类型)
复制代码
返回当前对象对应的值。(Object.valueOf()
至关于Object.Prototype.ValueOf()
)
咱们建立一个取代valueOf()
方法的函数,可是须要注意的是方法必须不能传入参数 。 假设咱们有个对象叫ObjectrType
而我想为它建立一个valueOf()
方法。下面的代码为valueOf()
方法赋予了一个自定义函数:
ObjectrType.prototype.valueOf = function() { return customValue; };
复制代码
有了这样的一个方法,下一次每当ObjectrType
要被转换为原始类型值时,JavaScript
在此以前会自动调用自定义的valueOf()
方法。 valueOf()
方法通常都会被JavaScript
自动调用,但咱们也能够像下面代码那样本身调用:
ObjectrType.valueOf()
复制代码
valueOf
一样适用于string
,number
, symbol
,boolean
,date
。
返回当前对象对应的字符串形式。
function Dog(name) {
this.name = name;
}
const dog1 = new Dog('Gabby');
Dog.prototype.toString = function dogToString() {
return '' + this.name;
}
console.log(dog1.toString()); // Gabby
复制代码
返回当前对象对应的模块字符串。
语法:obj.toLocaleString();
let foo = {};
foo.toLocaleString(); // "[object Object]"
复制代码
判断当前对象是否为另外一个对象的原型。 语法:Object.prototype.isPrototypeOf(targetObj)
const arr = [];
Array.prototype.isPrototypeOf(arr); // true
// 修改obj的原型
Object.setPrototypeOf(arr, String.prototype);
Array.prototype.isPrototypeOf(arr); // false
String.prototype.isPrototypeOf(arr); // true
复制代码
判断某个属性是否为当前对象自身的属性,仍是继承自原型对象的属性,并返回一个布尔值。
语法: Object.prototype.hasOwnProperty(prop)
let obj = {};// 定义一个object实例
obj.prop1 = 'value1'; // prop1是一个自有属性
obj.constructor.prototype.prop2 = 'value2'; // prop2是一个原型链属性
// 不管自有属性仍是原型链属性,咱们均可以访问到
console.info(obj.prop1); // value1
console.info(obj.prop2); // value2
// 使用`hasOwnProperty()`方法判断属性是否为自有属性
obj.hasOwnProperty('prop1'); // true
obj.hasOwnProperty('prop2'); // false
复制代码
判断某个属性是否可枚举。
语法: Object.prototype.propertyIsEnumerable(prop)
const obj = { name: 'ecmaer'};
Object.getOwnPropertyDescriptor(obj, 'name').enumerable; // true
obj.propertyIsEnumerable('name'); // true
// 将属性name设置成不可枚举
Object.defineProperty(obj, 'name', {enumerable: false});
obj.propertyIsEnumerable('name'); // false
for(let i in obj){
console.info(obj[i]); // 没有遍历出'ecmaer'
}
复制代码
typeof
可用来检测数据类型: 须要注意的是typeof
没法区分null
、Array
和 一般意义上的object
。
typeof 123 //number
typeof '123' //string
typeof true // boolean
typeof false //boolean
typeof undefined // undefined
typeof Math.abs // function
typeof function () {} // function
// 当赶上`null`、`Array`和一般意义上的`object`,都会返回 object
typeof null // object
typeof [] // 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()
运算符用于检测构造函数的 prototype
属性是否出如今某个实例对象的原型链
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); // true
console.log(auto instanceof Object); // true
复制代码
能够精准的判断对象类型。
对于array
、null
、object
来讲,其关系错综复杂,使用 typeof
都会统一返回 object
字符串,要想区别对象、数组、函数单纯使用typeof
是不行的,想要准确的判断对象类型,推荐使用Object.Prototype.toString()
,它能够判断某个对象值属于哪一种内置类型。
const arrs = [1,2,3];
console.log(typeof arrs) // object
console.log(Object.Prototype.toString.call(arrs)) // [object Array]
复制代码
call
直接调用该执行函数,在执行的时候,将函数内部的做用域绑定到指定的做用域。(call()
方法接受若干个参数的列表)
const arr = [2,5,4,7,6]
const a = Function.prototype.apply.call(Math.max, null,arr)
console.log(a) // 7
复制代码
apply
直接调用该执行函数,在执行的时候,将函数内部的做用域绑定到指定的做用域。
call()
是apply()
的一颗语法糖,做用和apply()
同样,一样可实现继承,惟一的区别就在于call()
接收的是参数列表,而apply()
则接收参数数组。
const arr = [2,5,4,7,6]
const a = Function.prototype.call.apply(Math.max, arr)
console.log(a) // 7
//若是apply的第二个参数是个null,会返回-Infinity
const b = Function.prototype.call.apply(Math.max, null, arr)
console.log(b) // -Infinity
复制代码
bind
建立一个新的函数的引用,并绑定到一个做用域特定做用域上,同时支持传参。
bind
则和call
的用法差很少,惟一区别是,call
和apply
会马上调用函数,bind
只是绑定this
格式为: bind
(做用域参数,参数1,参数2)
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 red
复制代码
this
对象;this
要指向的对象;thisObj
指定的新对象。bind()
是返回一个新函数,供之后调用,而apply()
和call()
是当即调用。call()
和apply()
惟一区别是参数不同,call()
是apply()
的语法糖;apply()
;call()
;bind()
;首先须要定义一个变量:
const date = new Date();
接下来就能够直接使用常见的Date对象方法。
console.log(date.getDate())
;看到评论有小哥(or小姐姐)说了简单的数组去重的方式,以前整理的时候只是简单的拓宽了如下,如今对与数组去重的几种方式在这里作一下概括:
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]
复制代码
比较简单并且稳妥的就这几种,其余的去重方式,能够考虑使用“递归”以及map
数据结构去重呀。
可能有童鞋以为还可使用includes
,sort
,indexOf
等方式去重,其实也是能够的,可是要注意这几种方式对于复杂的一维数组去重,可能会有些bug
,还须要本身去处理。
因此,能够掌握好上面几种简单的去重方式,必要的时候会节省不少时间。
整理至此,请用心记!!!!(记不住的欢迎下方👇戳小编,小编给您寄“拖鞋”)🤨
到这里基本梳理完了,越是细小的只是点越是要熟练掌握(按下ctl+f
查找会有惊喜哦(Mac
是command+f
),能够快速搜索)。之后不出意外会小编会两周一更,本篇梳理,会持续更新ing
。