最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一文掌握J(rèn)avaScript數(shù)組常用工具函數(shù)總結(jié)

 更新時(shí)間:2022年06月24日 14:22:36   作者:??pino????  
這篇文章主要介紹了一文掌握J(rèn)avaScript數(shù)組常用工具函數(shù)總結(jié),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值

一. 實(shí)現(xiàn)Array.isArray

if (!Array.isArray){
  Array.isArray = function(arg){
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

二. 將類數(shù)組轉(zhuǎn)換為數(shù)組

1. 借用數(shù)組的方法進(jìn)行轉(zhuǎn)換

// 1. slice
Array.prototype.slice.call(arguments)
// 2. concat
[].concat.apply([], arguments)

2. es6的方式轉(zhuǎn)換

// 1. ...擴(kuò)展運(yùn)算符
[...arguments]

// 2. Array.from()
Array.from(arguments)

三. 判斷是否為數(shù)組

var a = [];
// 1.基于instanceof
a instanceof Array;
// 2.基于constructor
a.constructor === Array;
// 3.基于Object.prototype.isPrototypeOf
Array.prototype.isPrototypeOf(a);
// 4.基于getPrototypeOf
Object.getPrototypeOf(a) === Array.prototype;
// 5.基于Object.prototype.toString
Object.prototype.toString.call(a) === '[object Array]';
// 6. 通過Array.isArray
Array.isArray(a)

四. 數(shù)組方法實(shí)現(xiàn)

1.forEach

 Array.prototype.myForEach = function(fn, context = window){
    let len = this.length
    for(let i = 0; i < len; i++){
        typeof fn === 'function' && fn.call(context, this[i], i)
    }
}

2. filter

Array.prototype.myFilter = function(fn, context = window){
    let len = this.length,
        result = []
    for(let i = 0; i < len; i++){
        if(fn.call(context, this[i], i, this)){
            result.push(this[i])
        }
    }
    return result
}

3. every

Array.prototype.myEvery = function(fn, context){
    let result = true,
        len = this.length
    for(let i = 0; i < len; i++){
        result = fn.call(context, this[i], i, this)
        if(!result){
            break
        }
    }
    return result
}

4. some

Array.prototype.mySome = function(fn, context){
    let result = false,
        len = this.length
    for(let i = 0; i < len; i++){
        result = fn.call(context, this[i], i, this)
        if(result){
            break
        }
    }
    return result
}

5. findIndex

Array.prototype.myFindIndex = function (callback) {
    for (let i = 0; i < this.length; i++) {
        if (callback(this[i], i)) {
            return i
        }
    }
}

6. Reduce

Array.prototype.myReduce = function (fn, initialValue) {
    let arr = Array.prototype.call(this)
    let res, startIndex
    res = initialValue ? initialValue : arr[0]
    startIndex = initialValue ? 0 : 1
    for (let i = startIndex; i < arr.length; i++) {
        res = fn.call(null, res, arr[i], i, this)
    }
    return res
}

五. 實(shí)現(xiàn)數(shù)組扁平化

let ary = [1, [2, [3, 4, 5]]]

1. 普通遞歸+concat

const flatten = function(ary){
    let result = []

    for(let i = 0;i<ary.length;i++){
        if(Array.isArray(ary[i])){
            result = result.concat(flatten(ary[i]))
        } else {
            result.push(ary[i])
        }
    }
    return result
}

2. reduce+concat

const flatten = function(ary){
    return ary.reduce((prev, next)=>{
        return prev.concat(Array.isArray(next) ? flatten(next) : next)
    }, [])
}

3. while+concat

const flatten = function(ary){
    while(ary.some(item=>Array.isArray(item))){
        ary = [].concat(...ary)
    }
    return ary
}

4. toString+split

const flatten = function(ary){
    return ary.toString().split(',')
}

5. flat

const flatten = function(ary){
    return ary.flat(Infinity)
}

6. 正則

const flatten6 = function(ary){
    let str = JSON.stringify(ary)
    str = str.replace(/([|])/g, '')
    return JSON.parse(`[${str}]`)
}

六. 去重

1. 利用 ES6 語(yǔ)法(擴(kuò)展運(yùn)算符)

const unique1 = (array) => {
  // return Array.from(new Set(array))
  return [...new Set(array)]
}

2. 利用 forEach() + 對(duì)象容器

const unique2 = (array) => {
  const arr = []
  const obj = {}
  array.forEach(item => {
    if (!obj.hasOwnProperty(item)) {
      obj[item] = true
      arr.push(item)
    }
  })
  return arr
}

3. 利用 forEach 和 indexOf

const unique3 = (array) => {
  const arr = []
  array.forEach(item => {
    if (arr.indexOf(item) === -1) {
      arr.push(item)
    }
  })
  return arr
}

4. 利用 filter + indexOf

const unique4 = (array) => {
  return array.filter((item,index) => {
    return array.indexOf(item) === index;
  })
}

5. 利用 forEach 和 includes (本質(zhì)同3)

const unique6 = (array) => {
  let result = [];
  array.forEach(item => {
    if(!result.includes(item)){
      result.push(item);
    }
  })
  return result;
 }

6. 利用 sort

const unique6 = (array) => {
  let result = array.sort(function (a,b) {
    return a - b;
  });
  for(let i = 0;i < result.length;i ++){
    if(result[i] === result[i+1]){
      result.splice(i + 1,1);
      i --;
    }
  }
  return result;
}

7. 雙層for循環(huán)

function unique(array) {
    // res用來存儲(chǔ)結(jié)果
    var res = [];
    for (var i = 0, arrayLen = array.length; i < arrayLen; i++) {
        for (var j = 0, resLen = res.length; j < resLen; j++ ) {
            if (array[i] === res[j]) {
                break;
            }
        }
        // 如果array[i]是唯一的,那么執(zhí)行完循環(huán),j等于resLen
        if (j === resLen) {
            res.push(array[i])
        }
    }
    return res;
}
console.log(unique(array)); // [1, "1"]

七. 排序

1. 冒泡排序

原理:利用數(shù)組的前一項(xiàng)與相鄰的后一項(xiàng)相比較,判斷大/小,交換位置

const bubbleSort = function(ary){
    for(let i = 0; i < ary.length - 1; i++){
        for(let j = 0; j < ary.length - 1 - i; j++){
            if(ary[j] > ary[j+1]){
                [ary[j], ary[j+1]] = [ary[j+1], ary[j]]
            }
        }
    }
    return ary
}

2. 選擇排序

原理:利用數(shù)組的某項(xiàng)與后面所有的值相比較,判斷大/小,交換位置

const bubbleSort = function(ary){
    for(let i = 0; i < ary.length - 1; i++){
        for(let j = i + 1; j < ary.length; j++){
            if(ary[i] > ary[j]){
                [ary[i], ary[j]] = [ary[j], ary[i]]
            }
        }
    }
    return ary
}

3. 原生排序

Array.sort((a, b)=>a-b)

4. 快速排序

原理:取數(shù)組的中間值作為基準(zhǔn),判斷左右兩邊的值大或小,添加到相應(yīng)數(shù)組,遞歸調(diào)用,然后將所有的值拼接在一起。

const quick_sort = function(ary){
    if(ary.length < 1){
        return ary
    }
    let centerIndex = Math.floor(ary.length/2)
    let centerVal = ary.splice(centerIndex, 1)[0]
    let left = []
    let right = []
    ary.forEach(item => {
        item > centerVal ? right.push(item) : left.push(item)
    })
    return [...quick_sort(left), ...[centerVal], ...quick_sort(right)]
}

5. 插入排序

原理:先將數(shù)組中的一項(xiàng)添加到新數(shù)組中,循環(huán)數(shù)組每一項(xiàng)與新數(shù)組中比較,比較大的值放在后面小的放到新數(shù)組的前面。

 const insertion_sort = function(ary){
    let newAry = ary.splice(0, 1)
    for(let i = 0; i < ary.length; i++){
        let cur = ary[i]
        for(let j = newAry.length - 1; j >= 0;){
            if(cur < newAry[j]){
                j--
                j === -1 && newAry.unshift(cur)
            } else {
                newAry.splice(j + 1, 0, cur)
                j = -1
            }
        }
    }
    return [...newAry]
}

八. 最大值與最小值

1. 假設(shè)法

const maxMin = function(ary){
    let [min, max] = [ary[0], ary[1]]
    ary.forEach(ele => {
        min > ele ? min = ele : null
        max < ele ? max = ele : null
    })
    return [min, max]
}

2. math.max() + 假設(shè)法

var arr = [6, 4, 1, 8, 2, 11, 23];
var result = arr[0];
for (var i = 1; i < arr.length; i++) {
    result =  Math.max(result, arr[i]);
}
console.log(result);

3. reduce

var arr = [6, 4, 1, 8, 2, 11, 23];
function max(prev, next) {
    return Math.max(prev, next);
}
console.log(arr.reduce(max));

4. 排序

var arr = [6, 4, 1, 8, 2, 11, 23];
arr.sort(function(a,b){return a - b;});
console.log(arr[arr.length - 1])

5. 利用Math.max

Math.max.apply(null, ary)
// 擴(kuò)展運(yùn)算符
Math.max(...arr)
// eval
var max = eval("Math.max(" + arr + ")");

九. 平均值

const balance = function(ary){
    ary.sort((a, b) => a - b)
    ary.shift()
    ary.pop()
    let num = 0
    ary.forEach(item => {
        num += item
    })
    return (num/ary.length).toFixed(2)
}

十. 數(shù)組亂序

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
    return a;
}

十一. 將數(shù)組扁平化并去除其中重復(fù)數(shù)據(jù),最終得到一個(gè)升序且不重復(fù)的數(shù)

let 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})

到此這篇關(guān)于一文掌握J(rèn)avaScript數(shù)組常用工具函數(shù)總結(jié)的文章就介紹到這了,更多相關(guān)JS數(shù)組工具內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • javascript 也來玩玩圖片預(yù)加載

    javascript 也來玩玩圖片預(yù)加載

    javascript 也來玩玩圖片預(yù)加載...
    2007-05-05
  • js 判斷checkbox是否選中的實(shí)現(xiàn)代碼

    js 判斷checkbox是否選中的實(shí)現(xiàn)代碼

    大家在很多場(chǎng)合也許會(huì)遇到判斷頁(yè)面是否有元素選中,下面介紹的是利用js判斷是否選中CheckBox的方法。
    2010-11-11
  • 搭建Bootstrap離線文檔的方法

    搭建Bootstrap離線文檔的方法

    雖然現(xiàn)在不聯(lián)網(wǎng)的情況很少,但在本機(jī)上搭建一份Bootstrap離線文檔以備不時(shí)之需也是很有必要的。下面就給大家分享下搭建Bootstrap離線文檔的方法,感興趣的朋友一起看看吧
    2016-12-12
  • 淺談js函數(shù)三種定義方式 & 四種調(diào)用方式 & 調(diào)用順序

    淺談js函數(shù)三種定義方式 & 四種調(diào)用方式 & 調(diào)用順序

    下面小編就為大家?guī)硪黄獪\談js函數(shù)三種定義方式 & 四種調(diào)用方式 & 調(diào)用順序。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-02-02
  • date.parse在IE和FF中的區(qū)別

    date.parse在IE和FF中的區(qū)別

    這個(gè)方法是很常用的,比如在驗(yàn)證輸入日期是否存在時(shí),可以使用它,如果是一個(gè)不存在的日期,則其返回值將是NaN,另外如果要比較兩個(gè)日期的先后,或是計(jì)算兩個(gè)日期相差的天數(shù) ,都可以用到。
    2010-07-07
  • 微信小程序移動(dòng)拖拽視圖-movable-view實(shí)例詳解

    微信小程序移動(dòng)拖拽視圖-movable-view實(shí)例詳解

    這篇文章主要介紹了微信小程序移動(dòng)拖拽視圖-movable-view的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-08-08
  • ES6解構(gòu)賦值實(shí)例詳解

    ES6解構(gòu)賦值實(shí)例詳解

    這篇文章主要介紹了ES6解構(gòu)賦值,結(jié)合實(shí)例形式較為詳細(xì)的分析了ES6結(jié)構(gòu)賦值的基本概念、原理與使用方法,需要的朋友可以參考下
    2017-10-10
  • 淺談JS封閉函數(shù)、閉包、內(nèi)置對(duì)象

    淺談JS封閉函數(shù)、閉包、內(nèi)置對(duì)象

    下面小編就為大家?guī)硪黄獪\談JS封閉函數(shù)、閉包、內(nèi)置對(duì)象。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07
  • JavaScript中DOM常見的操作匯總

    JavaScript中DOM常見的操作匯總

    DOM(文檔對(duì)象模型)是一種用于表示和操作HTML和XML文檔的標(biāo)準(zhǔn),在JavaScript中,可以使用DOM?API來對(duì)DOM進(jìn)行操作,下面就來看看常見的操作都有哪些吧
    2023-08-08
  • 微信小程序?qū)崿F(xiàn)簡(jiǎn)單聊天室

    微信小程序?qū)崿F(xiàn)簡(jiǎn)單聊天室

    這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)簡(jiǎn)單聊天室,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07

最新評(píng)論

鄂尔多斯市| 淳安县| 满城县| 曲沃县| 呼和浩特市| 东城区| 镇赉县| 大同市| 东丽区| 马公市| 松阳县| 东兰县| 缙云县| 高邮市| 云林县| 申扎县| 汉源县| 上饶市| 南宫市| 义乌市| 澜沧| 筠连县| 平果县| 平潭县| 宜黄县| 朝阳区| 湟中县| 惠水县| 应城市| 天长市| 金坛市| 九寨沟县| 壤塘县| 原平市| 买车| 贡嘎县| 大丰市| 白朗县| 惠安县| 双牌县| 崇明县|