JavaScript常用方法汇总(供小白食用)

199 阅读17分钟

前言:此笔记为参考👉mp.weixin.qq.com/s/BUuFi1uqG…

自己为菜鸟对着原文全过了一遍并对小部分内容订正修改,大家喜欢可关注链接内原作者。

感谢。

✨ Array

newSet():

用来对数组进行去重

let arr=[1,2,3,2,3,2,4,5]
console.log(new Set(arr));  // {1, 2, 3, 4, 5}

// Array.from():方法从[类似数组]或[可迭代对象]创建一个新的(浅拷贝)的[数组实例]
let a=Array.from(new Set(arr))  
console.log(a);  // [1, 2, 3, 4, 5]

sort()

对数组进行排序(改变原数组)

默认是按照最左边的数字进行排序,不是按照数字大小排序的)

let arr=[1,2,3,2,3,2,4,5,11,22]
// 默认编码顺序排序
console.log(arr.sort());  // [1, 11, 2, 2, 2, 22, 3, 3, 4, 5]
// 升序
console.log(arr.sort((a,b)=>a-b));  // [1, 2, 2, 2, 3, 3, 4, 5, 11, 22]
// 降序
console.log(arr.sort((a,b)=>b-a));  // [22, 11, 5, 4, 3, 3, 2, 2, 2, 1]

reverse()

反转数组中的元素 (改变原数组)

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.reverse());  // [7, 6, 5, 5, 4, 4, 4, 3]
console.log(arr); // [7, 6, 5, 5, 4, 4, 4, 3]

delete

删除一个数组成员,会形成空位,并不会影响length属性,同样适用于对象 (改变原数组)。

//数组
const arr = [3, 4, 4, 5, 4, 6, 5, 7];
delete arr[1];
console.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"}

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]

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]

pop()

把数组的最后一个元素从其中删除,并返回最后一个元素的值(改变原数组)

const arr = [3, 4, 4, 5, 4, 6, 5, 7];
const a=arr.pop()
console.log(a); // 10(a为返回的数组的新长度)
console.log(arr);

shift()

把数组的第一个元素从其中删除,并返回第一个元素的值 (改变原数组)。

const arr = [3, 4, 4, 5, 4, 6, 5, 7];
const a = arr.shift();
console.log(arr);  // [4, 4, 5, 4, 6, 5, 7]
console.log(a);  // 返回删除的第一个元素的值

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); 
console.log(c)  // [1,2,3,4,5]
//字符串
const x = 'abc';
const y = 'def';
const z = x.concat(y); 
console.log(z) // abcdef

slice(start, end)

用于截取原来数组的一部分,会返回一个截取的新数组,原数组不变 (字符串适用,不包括end)。

//数组
const arr = [3, 4, 4, 5, 4, 6, 5, 7];
const a = arr.slice(2, 5); 
console.log(a); // [4, 5, 4]
console.log(arr); // [3, 4, 4, 5, 4, 6, 5, 7]

//字符串
const x = 'abcdefgh';
const y = x.slice(3, 6); 
console.log(y); // def
console.log(x); // abcdefgh

splice(index,howmany,item1,...itemX)

可以用来数组删除和添加,会改变原来的数组,返回值是被删除的数组元素。

  • index: 规定添加/删除项目的位置,使用负数可从数组结尾处规定位置
  • howmany: 要删除的项目数量。如果设置为 0,则不会删除项目
  • item1, …, itemX: 向数组添加的新项目
const arr = [3, 4, 4, 5, 4, 6, 5, 7];
const a = arr.splice(3, 2, 12); 
console.log(arr); // [3, 4, 4, 12, 6, 5, 7]
console.log(a); // [5, 4] 

join()

数组变成字符串,默认逗号隔开,join中可添加任意你想隔开的字符(不改变原数组)。

const arr = [3, 4, 4, 5, 4, 6, 5, 7];
const a = arr.join(""); 
console.log(arr); // [3, 4, 4, 5, 4, 6, 5, 7];
console.log(a); // 34454657

split()

用于把一个字符串转化为数组(不改变原数组)。

const arr = "hello";
const a = arr.split(""); 
const b = arr.split("",2)
console.log(arr); // hello
console.log(a); // ['h', 'e', 'l', 'l', 'o']
console.log(b); // ['h', 'e']

map()

依次遍历数组成员,根据遍历结果返回一个新数组(不会改变原数组)。数组中的元素为原始数组元素调用函数处理后的值

map() 方法按照原始数组元素顺序依次处理元素

map() 不会对空数组进行检测。

const arr = [3,4,4,5,4,6,5,7];
const a = arr.map(item => item*2;) 
console.log(a) // [6, 8, 8, 10, 8, 12, 10, 14]

let arr = ['小明', '小花', '小涛']; 
let newArr = arr.map((item, index)=>{ 
    return { 
        name: item, 
        id: index 
    } 
}); 
console.log(newArr); 
//输出结果:[{name: "小明", id: 0}, {name: "小花", id: 1}, {name: "小涛", id: 2}]

forEach()

map方法类似,遍历数组,区别是无返回值。

const arr = [3, 4, 4, 5, 4, 6, 5, 7];
arr.forEach((item, index) => { console.log(item) }) // 依次打印数组值

filter()

一个过滤方法,参数是一个函数,所有的数组成员依次执行该函数,返回结果为 true 的成员组成一个新数组返回。(不会改变原始数组)

const arr = [3,4,4,5,4,6,5,7];
const a = arr.filter(item => item % 3 > 1);
console.log(a); // [5, 5] 余数大于1

let arr = [
{ name: '小明', id: '1' },
{ name: '小花', id: '2' },
{ name: '小明', id: '3' }
] 
// 过滤出name为小明的那一项 
let newArr = arr.filter(item=>item.name == '小明');
console.log(newArr); 
// 输出结果 [{name: "小明", id: "1"}, {name: "小明", id: "3"}]

reduce()

reduce() 方法接收一个函数,依次处理数组的每个成员,最终累计成一个值。

arr.reduce(function(prev,cur,index,arr){ ... }, init); 
arr  | 表示原数组; 
prev | 表示上一次调用回调时的返回值,或者初始值 init; 
cur  | 表示当前正在处理的数组元素; 
index | 表示当前正在处理的数组元素的索引,若提供 init 值,则索引为0,否则索引为1; 
init | 表示初始值。

//简单用法
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()

reduce 方法使用方式相同,区别在于 reduceRight 方法从右到左执行

some()

用于检测数组中的元素是否满足指定条件,只要有一个数组成员的返回值为true,则返回true,否则false;(不会改变原数组)

let arr = [
{ name: '小明', id: 1 },
{ name: '小明', id: 2 }
]; 
let a = arr.some(item=>{ return item.name == '小明' }) 
console.log(a); // true 
let b = arr.some(item=>{ return item.id == 1 }) 
console.log(b); // true

every()

检测数组所有元素是否都符合指定条件,需要每一个返回值为true,才能返回true,否则为false(不会改变原数组)

let arr = [
{ name: '小明', id: 1 },
{ name: '小明', id: 2 }
]; 
let a = arr.every(it=>{ return it.name == '小明' }) 
console.log(a); // true 
let b = arr.every(it=>{ return it.id == 1 }) 
console.log(b); // false

indexOf()

返回给定元素在数组中的第一次出现的位置,如果没有则返回-1 (同样适用于字符串)。

//数组\
const arr = [3,4,4,5,4,6,5,7];
console.log(arr.indexOf(4)) // 1
console.log(arr.indexOf('4'))  // -1

//字符串
conststring = 'asdfghj';
console.log(string.indexOf('a')) // 0

lastIndexOf()

返回给定元素在数组中最后一次出现的位置,如果没有就返回-1 (同样适用于字符串)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.lastIndexOf(4));
// 4 (从左到右数最后出现的位置,字符串同理)

find()

返回符合传入函数条件的第一个数组元素,没有符合则返回undefined

const arr = [3, 4, 4, 5, 4, 6, 5, 7];
const a = arr.find(item => item > 3);
console.log(a); // 4 

const b = arr.find(item => item == 0);
console.log(b); // undefined(如果没有符合条件的元素返回 undefined)

flatten()

简写为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]

for in()

map方法类似,遍历对象或者数组。 但值得注意的是 for in 循环返回的值都是数据结构的键值名 。遍历对象返回的对象的key值,遍历数组返回的数组的下标 (key)

// 对象
const obj = {a123b12c2 };
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)} // 0123

Array.isArray()

用来判断是不是数据是不是一个数组,返回值为truefalse

const arr = [3,4,4,5,4,6,5,7];
console.log(Array.isArray(arr)) // true

copyWithin()

从数组的指定位置拷贝元素到数组的另一个指定位置中。

array.copyWithin(target,start,end)
target| 必需。复制到指定目标索引位置。                              
start | 可选。元素复制的起始位置。                                 
end   | 可选。停止复制的索引位置 (默认为 *array*.length)。如果为负值,表示倒数。

// 复制数组的前面两个元素到后面两个元素上:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0); // Banana,Orange,Banana,Orange

// 复制数组的前面两个元素到第三和第四个位置上:
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
fruits.copyWithin(2, 0, 2); // Banana,Orange,Banana,Orange,Kiwi,Papaya

✨ String

charAt()

用于返回指定位置的字符

const str = 'hello guys';
console.log(str.charAt(3))  // l

charCodeAt()

用于返回指定位置的字符的Unicode编码

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()

用于检索与字符串匹配的子串,返回的是地址,与 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,只能匹配字符串)

includes()

用于判断字符串是否包含指定的子字符串。如果找到匹配的字符串则返回 true,否则返回 false

注意:  includes() 方法区分大小写。

var str = "Hello world, welcome to the Runoob。"; 
var n = str.includes("Runoob"); // true

string.includes(searchvalue, start)
searchvalue | 必需,要查找的字符串。           |
start       | 可选,设置从那个位置开始查找,默认为 0var str = "Hello world, welcome to the Runoob."; 
var n = str.includes("world", 12); // false

toLocaleLowerCase()& toLowerCase()

将字符串转换成小写

const str = 'hello guys';
console.log(str.toLocaleLowerCase())  // hello guys
console.log(str.toLowerCase())  //  hello guys

toLocaleUpperCase() & toUpperCase()

将字符串转换成大写

const str = 'hello guys';
console.log(str.toLocaleUpperCase())  // HELLO GUYS
console.log(str.toUpperCase())  // HELLO GUYS

substr()

用于从起始索引号提取字符串中指定数目的字符

const str = 'hello guys';
console.log(str.substr(2))  // llo guys
console.log(str.substr(27))  // llo guy

substring()

用于提取字符串中两个指定索引号之间的字符,返回的子串包括开始处的字符,但不包括结束处的字符(空格也算一字符)。(与 slice()substr() 方法不同的是, substring() 不接受负的参数。)

const str = 'hello guys';
console.log(str.substring(2))   // llo guys
console.log(str.substring(27))  //  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()

方法返回指定对象的原始值

默认情况下,valueOf 方法由 Object 后面的每个对象继承。 每个内置的核心对象都会覆盖此方法以返回适当的值。如果对象没有原始值,则 valueOf 将返回对象本身。

image.png

参考👉:developer.mozilla.org/zh-CN/docs/…

Object.Prototype.toString()

返回当前对象对应的字符串形式

function Dog(name) {
    this.name = name;
}
const dog1 = new Dog('Gabby');
Dog.prototype.toString = function dogToString() {
    return '' + this.name;
}
console.log(dog1.toString()
);  // Gabby

Object.Prototype.toLocaleString()

返回当前对象对应的模块字符串。 语法:obj.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); // false
String.prototype.isPrototypeOf(arr); // true

Object.Prototype.hasOwnProperty()

判断某个属性是否为当前对象自身的属性,还是继承自原型对象的属性,并返回一个布尔值

语法:Object.prototype.hasOwnProperty(prop)

let obj = {};
// 定义一个object实例
obj.prop1 = 'value1';
// prop1是一个自有属性
obj.constructor.prototype.prop2 = 'value2';
// prop2是一个原型链属性

// 无论自有属性还是原型链属性,我们都可以访问到
console.log(obj.prop1); // value1
console.log(obj.prop2); // value2

// 使用`hasOwnProperty()`方法判断属性是否为自有属性
obj.hasOwnProperty('prop1'); // true
obj.hasOwnProperty('prop2'); // false

Object.Prototype.PropertyIsEnumerable()

判断某个属性是否可枚举。 语法:Object.prototype.propertyIsEnumerable(prop)

const obj = { name'ecmaer'};
Object.getOwnPropertyDescriptor(obj, 'name').enumerable// true
obj.propertyIsEnumerable('name'); // true

// 将属性name设置成不可枚举
Object.defineProperty(obj, 'name', {enumerablefalse});
obj.propertyIsEnumerable('name'); // false
for(let i in obj){console.log(obj[i])}; // 没有遍历出'ecmaer'

✨ 判断一个值的类型的办法

typeOf()

可用来检测数据类型: 需要注意的是 typeof 无法区分 nullArray 和 通常意义上的 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 属性是否出现在某个实例对象的原型链

能够区分ArrayObject和Function,适合用于判断自定义的类实例对象

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

// 不能判断基本数据类型:
console.log(11 instanceof Number);             // false
console.log(true instanceof Boolean);         // false 
console.log('str' instanceof String);         // false  
// 能够区分`Array`、`Objec`t和`Function`
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true

Object.Prototype.toString() (推荐)

可以精准的判断对象类型。 对于 array nullobject 来说,其关系错综复杂,使用 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,apply以及bind的用法,区别及相似处

call() 方法调用一个对象,可以改变 this 指向

function.call(thisArg, arg1, arg2,……)

// thisArg: 当前调用函数 this 的指向对象
// arg1, arg2: 传递的其他参数

function Animal(){
    // this 指向小cat
    this.eat =function (){
        console.log("吃东西");
    }
}
function Cat(){
    // this 指向小cat
    Animal.call(this) 
}
let cat =new Cat()
cat.eat() // 吃东西(继承,也可多重继承)

apply() 方法调用一个函数,可以改变 this 指向(同样可实现继承)。

fun.apply(thisArg, [argsArray])

// thisArg: 在 fun 函数运行时指定的 this 值
// argsArray: 传递的值,必须包含在数组里
// 返回值就是函数的返回值,因为它就是调用函数

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.maxnull, arr)
console.log(b)  // -Infinity

bind() 方法不会调用函数,但能改变 this 指向

function.bind(thisArg, arg1, arg2,……)

// thisArg: 在 fun 函数运行时指定的 this 值
// arg1, arg2: 传递的其他参数
// 返回由指定的 this 值和初始化参数改造的原函数拷贝

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();

主要应用场景

  • call 经常做继承。
  • apply 经常跟数组有关系,比如借助于数学对象实现数组最大值、最小值。
  • bind 不调用函数,但还想改变 this 指向时使用,比如改变定时器内部的 this 指向。

✨ Data对象的用法

首先需要定义一个变量:

const date = new Date();

接下来就可以直接使用常见的Date对象方法

Date():  返回当日的日期和时间;

getDate(): 从Date对象返回一个月中的某一天(131)console.log(date.getDate());

getDay():从Date对象返回一周中的某一天(06);

getMonth(): 从Date对象返回月份(011);

getFullYear(): 从Date对象以四位数字返回年份;

getYear():可以使用getFullYear()代替;

gethours(): 返回Date()对象的小时(023);

getMinutes(): 返回Date()对象的分钟(059);

getSeconds(): 返回Date()对象的分钟(059);

getMillseconds(): 返回Date()对象的毫秒(0999);

getTime(): 返回197011日至今的时间;

getTimezoneOffset(): 返回本地时间与格林威治标准时间(GMT)的分钟差;

getUTCDate(): 根据世界时从Date对象返回月中的一天(131);

getUTCDay(): 根据世界时从Date对象返回周中的一天(16);

getUTCMonth(): 根据世界时从Date对象返回月份(011);

getUTCFullYear(): 根据世界时从Date对象返回四位数的年份;

getUTCHours(): 根据世界时从Date对象返回对象的小时(023);

getUTCMinutes(): 根据世界时从Date对象返回对象的分钟(059);

getUTCSeconds(): 根据世界时从Date对象返回对象的秒钟(059);

getUTCMillseconds(): 根据世界时从Date对象返回对象的毫秒(0999);

parse(): 返回197011日午夜到指定日期(字符串)的毫秒数;

setDate(): 设置Date对象中月的某一天(131);

setMonth(): 设置Date对象中月份(011);

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]

// 函数封装
var arr1 = [1,2,3,2,4,1];
function unique(arr){
    return [...new Set(arr)]
}
console.log(  unique(arr1) ); // [1, 2, 3, 4]

recude+include去重

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 arr1 = [4, 5, 3, 4, 6, 5, 8, 6];
function unique(arr){
    return arr.reduce((pre,cur)=>pre.includes(cur)?pre:[...pre,cur],[])
}
console.log(unique(arr1)); // [4, 5, 3, 6, 8]

indexOf

var arr2 = [1,2,3,2,4,1];
function unique( arr ){
    var brr = [];
    for( var i=0;i<arr.length;i++){
        if(  brr.indexOf(arr[i]) == -1 ){
                brr.push( arr[i] );
        }
}
    return brr;
}
console.log( unique(arr2) ); // [1, 2, 3, 4]

利用filter去重

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]

// 函数封装
var arr3 = [1,2,3,2,4,1];
function unique( arr ){
	return arr.filter(function(item,index,arr){
	//当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素
            return arr.indexOf(item,0)===index
	})
}
console.log( unique(arr3) ); // [1, 2, 3, 4]