JS常用小功能

個人博客:http://blog.lvxiang.site/JS常用小功能/

目錄

  1. 數組去重
  2. 字符串反轉
  3. 數組去扁平化並去重排序
  4. 判斷數組的方法

正文

  • 數組去重(es6)
    const arr = ['🙂', 7, '🙂', '😡'];
    // 1.Set
    [...new Set(arr)];
    // 或者
    Array.from(new Set(arr));
    
    // 2.Filter
    arr.filter((item, index) => arr.indexOf(item) === index);
    
    // 3.Reduce
    /*  reducer 函數接收4個參數:
    	1.Accumulator (acc) (累計器)
    	2.Current Value (cur) (當前值)
    	3.Current Index (idx) (當前索引)
    	4.Source Array (src) (源數組)
    */
    arr.reduce((acc, cur) => 
    	return acc.includes(cur) ? acc : [...acc, cur], []);
    	
    // 4.Object 鍵值對
    array.filter(function(item, index, array){
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
    })
    
    // 5.Map
    const seen = new Map()
    arr.filter((a) => !seen.has(a) && seen.set(a, 1))
    
  • 字符串反轉
    const str = 'abcdef123';
    console.log(str.split('').reverse().join(''));
    
  • 數組去扁平化並去重排序
    var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
    Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})
    
  • 判斷數組的方法
    const arr = [];
    // 1. Array對象方法
    Array.isArray(arr); //true
    // 2. instanceof
    arr instanceof Array; //true
    // 3.constructor
    arr.constructor.name === 'Array'; // true
    // 4.Obecjt的toString方法
    Object.prototype.toString.call(arr) === '[object Array]'; //true
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章