一盞茶的時間,快速捕獲JS中經常使用的方法(細心整理,持續更新ing)

不知不覺上班一週遼~趁着大好週末,小編掙扎着從牀上爬起來,決定對前端平常編程中經常使用到的一些方法作一個系統的整合。前端

有些人或許會以爲忘了百度就完事兒,no no no!這事兒小編真的親踐過好屢次,百度一次記住了還好,記不住下次碰着了還得找度娘簡直是拉低工做效率。正則表達式

本次整理但願能夠幫助到須要的童鞋,閒暇無聊多瞅幾眼保證能記住(記不住歡迎下方戳小編,小編必定給各位大佬寄「拖鞋」)。由於js這類的方法(技巧)總有新玩法,本篇文檔會持續更新,建議收藏。算法


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

反轉數組中的元素(改變原數組)。bash

const arr = [3,4,4,5,4,6,5,7];
conosle.log(arr.reverse());  // [7, 6, 5, 5, 4, 4, 4, 3]
複製代碼

delete

刪除一個數組成員,會造成空位,並不會影響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"}
複製代碼

shift()

把數組的第一個元素從其中刪除,並返回第一個元素的值(改變原數組)。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]
複製代碼

unshift()

向數組的起始處添加一個或多個元素,並返回新的長度(改變原數組)。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]
複製代碼

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)

用於提取原來數組的一部分,會返回一個提取的新數組,原數組不變(字符串適用,不包括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()

用於刪除原數組的一部分,而且能夠在刪除的位置添加新的數組成員,返回值是被刪除的數組元素。(改變原數組)

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

依次遍歷數組成員,根據遍歷結果返回一個新數組。(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]
複製代碼

forEach()

跟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
複製代碼

for in()

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
複製代碼

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]
複製代碼

some()& every()

這兩個方法相似於「斷言」(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
複製代碼
some方法是隻要有一個數組成員的返回值爲true,則返回true,不然false;
every方法是須要每個返回值爲true,才能返回true,不然爲false;

reduce()

依次處理數組的每一個成員,最終累計成一個值。

格式:

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的用法還有不少,剋各類嘗試。

reduceRight()

reduce方法使用方式相同,區別在於reduceRight方法從右到左執行(例子略過)。

indexOf()

返回給定元素在數組中的第一次出現的位置,若是沒有則返回-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
複製代碼

lastIndexOf()

返回給定元素在數組中最後一次出現的位置,沒有返回-1(一樣適用於字符串)。

const arr = [3,4,4,5,4,6,5,7];
console.log(arr.lastIndexOf(4)) 
// 4(從左到右數最後出現的位置,字符串同理)
複製代碼

groupBy()

把集合的元素按照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}

複製代碼

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

簡寫爲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]
複製代碼

Array.isArray()

用來判斷是否是數據是否是一個數組,返回值爲true或false。

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

用於返回指定位置的字符的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,只能匹配字符串)
複製代碼

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 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(2, 7))  // llo guy
複製代碼

substring()

用於提取字符串中兩個指定索引號之間的字符。(與 slice()substr() 方法不一樣的是,substring() 不接受負的參數。)

const str = 'hello guys';
console.log(str.substring(2))   // llo guys
console.log(str.substring(2, 7))  //  llo g
複製代碼

.trim()

去掉字符串兩端的空格。

const str = ' hello guys ';
console.log(str.trim()) // hello guys(不會改變原數組)
複製代碼

經常使用的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()

返回當前對象對應的值。(Object.valueOf()至關於Object.Prototype.ValueOf()

咱們建立一個取代valueOf()方法的函數,可是須要注意的是方法必須不能傳入參數 。 假設咱們有個對象叫ObjectrType而我想爲它建立一個valueOf()方法。下面的代碼爲valueOf()方法賦予了一個自定義函數:

ObjectrType.prototype.valueOf = function() { return customValue; };
複製代碼

有了這樣的一個方法,下一次每當ObjectrType要被轉換爲原始類型值時,JavaScript在此以前會自動調用自定義的valueOf()方法。 valueOf()方法通常都會被JavaScript自動調用,但咱們也能夠像下面代碼那樣本身調用:

ObjectrType.valueOf()
複製代碼

valueOf一樣適用於stringnumbersymbolbooleandate

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.info(obj.prop1); // value1
console.info(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', {enumerable: false});
obj.propertyIsEnumerable('name'); // false


for(let i in obj){
    console.info(obj[i]); // 沒有遍歷出'ecmaer'
}
複製代碼

Javascript的三種判斷一個值的類型的辦法

typeOf()

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

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
複製代碼

Object.Prototype.toString()(推薦)

能夠精準的判斷對象類型。

對於arraynullobject來講,其關係錯綜複雜,使用 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

    直接調用該執行函數,在執行的時候,將函數內部的做用域綁定到指定的做用域。(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的用法差很少,惟一區別是,callapply會馬上調用函數,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();

Date對象的用法

首先須要定義一個變量:

const date = new Date();

接下來就能夠直接使用常見的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對象的原始值。

一更😤: 簡單的數組去重

看到評論有小哥(or小姐姐)說了簡單的數組去重的方式,以前整理的時候只是簡單的拓寬了如下,如今對與數組去重的幾種方式在這裏作一下概括:

最便捷的方法: [...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]
複製代碼

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]
複製代碼

利用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]
複製代碼

利用hasOwnProperty去重

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查找會有驚喜哦(Maccommand+f),能夠快速搜索)。之後不出意外會小編會兩週一更,本篇梳理,會持續更新ing

(暗戳戳附上閨蜜男神圖但願不被看到嘿嘿)
相關文章
相關標籤/搜索