01-JavaScript常見的數(shù)組方法

JavaScript常見的數(shù)組方法

pop()

  • pop()方法會從數(shù)組中刪除最后一個元素,并返回最后一個元素.
    const arrs = [1,2,3,4,5]
    const res = arrs.pop()
    console.log(res)   // 5

push()

  • push()方法允許你向數(shù)組中添加一個或多個元素
  • push()會返回新增數(shù)組后新的長度
    const arrs = [1,2,3,4,5]
    let res = arrs.push(888);
    console.log(arrs) // [1, 2, 3, 4, 5, 888]
    console.log(res)  // 6 得到新的數(shù)組長度

shift()

  • shift()方法會刪除數(shù)組的第一個元素并返回它
    const arrs = [1,2,3,4,5]
    const res = arrs.shift()
    console.log(res)   // 1

unshift()

  • unshift()方法允許向數(shù)組的開頭添加一個或多個元素
  • 會將新增后的數(shù)組長度返回
   const arrs = [1,2,3,4,5]
   let res = arrs.unshift(888);
   console.log(arrs) // [888, 1, 2, 3, 4, 5]
   console.log(res)  // 6 得到新的數(shù)組長度

清空數(shù)組的幾種方式

  • 1.如何清空數(shù)組
    let arr = [1,2,3,4,5];
    // 清空數(shù)組的三個方法;
    // 第一種:直接將空數(shù)組賦值給數(shù)組
    arr = [];
    // 設置數(shù)組的長度為0
    arr.length = 0;
    // 利用splice
    arr.splice(0, arr.length);
    console.log(arr);

includes()

  • includes作用就是判斷元素元素是否在數(shù)組中,
    • 如果數(shù)組中有這個元素就返回true,否則返回的是false
    const arrs = [1,2,3,4,5]
    // const hasParam = arrs.includes(2)   // true
    const hasParam = arrs.includes('2')  // false
    console.log(hasParam)

concat()

  • 數(shù)組與數(shù)組間的拼接不可以使用+加號進行拼接,如果使用加號進行拼接會將數(shù)組轉換成字符串進行拼接
  • 使用concat()方法可以將兩個或多個數(shù)據(jù)組合起來,返回一個新的數(shù)組
  • 注意點:不會修改原有的數(shù)組;
  • 該方法的代替方式可以使用ES6的解構來實現(xiàn)
    const arr1 = [1,3]
    const arr2 = [2,4]
    const arr3 = [5,6]
    // + 加號拼接數(shù)組
    const str = arr1 + arr2;
    console.log(str);  // 1,32,4
    console.log(typeof str); // string

    // const res = arr1.concat(arr2)
    // console.log(res);  //[1, 3, 2, 4]
    const res = arr1.concat(arr2,arr3)
    console.log(res);  // [1, 3, 2, 4, 5, 6]

    // 補充: 可以使用擴展運算符來拼接數(shù)組
    // 解構數(shù)組中會將解構出來的元素放在新的數(shù)組中,返回給我們
    let res1 = [...arr1, ...arr2, ...arr3];
    console.log(res1);  //  [1, 3, 2, 4, 5, 6]
    console.log(typeof res1) // obj

    // 自定義函數(shù)合并任意多個數(shù)組
    function concatAll(arr, ...arrays){
        return arr.concat(...arrays)
    }
    console.log(concatAll(arr1,arr2,arr3));  // [1, 3, 2, 4, 5, 6]

forEach()

  • 當你想要對一個數(shù)組進行遍歷操作時,可以使用forEach()方法,它接受一個函數(shù)作為參數(shù)。事實上它本身接受三個參數(shù):(當前值,索引,數(shù)組)
    const arrs = [1,2,3,4,5]
    arrs.forEach(console.log)  // 當前值  索引 和數(shù)組
    arrs.forEach((value,index,arr)=>{
        console.log(value);
        console.log(index);
        console.log(arr);

    })

indexOf()

  • indexOf(檢索值,開始查找的位置)
  • indexOf作用: 返回數(shù)組中給定元素的第一個索引值. indexOf()也被用于檢查元素是否存在某一個元素
  • indexOf()方法從左到右開始查到,找到元素就停止查找
  • 注意點: 找到元素就會返回元素的對應位置,沒有找到元素就返回-1
    let arrs = [1,2,3,4,5,3]
    let index = arrs.indexOf(3);
    console.log(index);  // 2
    index = arrs.indexOf(3,4);
    console.log(index)  // 5
     

lastIndexOf()

  • 該方法和indexOf()方法使用和傳參一樣,但是查找方式是從右到左開始查找

find()

  • find()方法就是會查找數(shù)組中的元素,
  • find()方法找到了就會返回找到的元素,如果找不到就返回undefined
  • find()和filter()相似,但是find()函數(shù)找到一個匹配值就會停止查找,而filter會繼續(xù)查找
    const arrs = [1,2,3,4,5,4,3,2,1]
    const res = arrs.find(arr=> arr == 5)
    console.log(res)  // 5

    const obj = [
        {
            name: 'zs',
            age:12
        },
        {
            name: 'ww',
            age:33
        },
        {
            name: 'zs',
            age:16
        },
        {
            name: 'll',
            age:14
        },
    ]
    const res1 = obj.find(obj=> obj.name == 'zs')
    console.log(res1)  // {name: "zs", age: 12}

  • 如果是過濾整個數(shù)組那么采用filter,搜索數(shù)組中唯一元素時,則使用find()

findIndex()

  • 它和find()方法相同,只是他返回的是找到第一個元素的索引值,而不是元素
    const obj = [
        {
            name: 'zs',
            age:12
        },
        {
            name: 'ww',
            age:33
        },
        {
            name: 'zs',
            age:16
        },
        {
            name: 'll',
            age:14
        },
    ]
    const res2 = obj.findIndex(obj=> obj.name == 'ww')
    console.log(res2)  // 2

  • 你可能會認為findIndex()和indexOf()是相同的。事實上他們還是有所差異的。indexOf()的第一個參數(shù)是一個原始值(Boolean、Number、String、Null、Undefined或Symbol),而findIndex()的第一個參數(shù)是一個回調(diào)函數(shù)。

  • 因此,當你需要搜索原始值數(shù)組中元素的索引時,可以使用indexOf()。如果你有更復雜的元素,如對象,那得使用findIndex()。

slice()

  • slice方法可以幫助我們提取數(shù)組的一部分
  • 返回一個新的數(shù)組,不會修改原數(shù)組
  • slice方法是包含開始索引不包含結束索引 [開始索引,結束索引)
    let arr = [1,2,3,4,5];
    let res = arr.slice(1,3);
    console.log(res); // [2, 3]
    console.log(arr); // [1, 2, 3, 4, 5]

splice()

  • splice()通常用于添加或刪除某個所引出的元素.
  • splice(開始位置(必需),刪除數(shù)量(必需),item1,...item2(可選添加的項))

let arr = [1,2,3,4,5];
// arr.splice(1,3);
// console.log(arr) // [1, 5]

arr.splice(1,3,111,2222);
console.log(arr) // [1, 111, 2222, 5]

some()

  • some方法:檢測數(shù)組中至少有一個元素通過了測試
  • some()方法將回調(diào)函數(shù)作為唯一的參數(shù)
  • 如果至少有一個元素通過測試,則返回true,否則返回false。

every()

  • every()和some()類似,不同的是some()只要有一個元素符合條件就返回true,而every是所有元素都滿足條件才返回true

toString()

  • 將數(shù)組轉換成字符串
       let arr = [1,2,3,4,5];
       let str = arr.toString();
       console.log(str)  // 1,2,3,4,5
       console.log(typeof str) // string
    

join()

  • join()方法沒有傳遞參數(shù),調(diào)用toString()方法
  • join()方法可以傳遞參數(shù),把參數(shù)作為元素間的連接符號
    let arr = [1,2,3,4,5];
    let str = arr.join("-");
    console.log(str)  // 1-2-3-4-5
    console.log(typeof str) // string

isArray()

  • isArray()方法判斷傳遞的值是否為數(shù)組,是數(shù)組返回true,否則返回false

sort()

  • sort()方法會對數(shù)組中的元素進行排序.
  • 默認的排序方法將所有元素轉換為字符串,并按字母的順序排序
    const fruits = ['banana', 'apple','orange','pear']
    fruits.sort()
    console.log(fruits)  // ["apple", "banana", "orange", "pear"] 默認按字母的順序
  • 但是對于數(shù)字
      const nums = [3,72,33,42,5,8]
      nums.sort()
      console.log(nums)  // [3, 33, 42, 5, 72, 8]
    
    
  • 對于數(shù)字,sort()接受了一個比較函數(shù),并傳遞兩個參數(shù)
  • 參數(shù)分別為a,b;然后對這兩個元素進行比較,并且返回一個數(shù)字
  • 返回規(guī)則:
    • 如果返回的值是一個負數(shù),則表示a排在b之前(升序)
    • 如果返回的值是一個正數(shù),則表示a排在b之后(降序)
    • 如果返回的值是0,則沒有變化
    const nums = [3,72,33,42,5,8]
    nums.sort((a,b)=> a-b)
    console.log(nums)  // [3, 5, 8, 33, 42, 72] 升序
    nums.sort((a,b)=> b-a)
    console.log(nums) // [72, 42, 33, 8, 5, 3] 降序

reverse()

  • reverse()方法就是將數(shù)組反轉
  • 注意點: 該方法會修改原有的數(shù)組
    const nums = [3,72,33,42,5,8]
    nums.reverse()
    console.log(nums) // [8, 5, 42, 33, 72, 3]

map()

  • map作用:修改數(shù)組的元素
  • map()方法會創(chuàng)建一個新數(shù)組,其結果是該數(shù)據(jù)中的每個元素都調(diào)用一個提供的函數(shù)后返回的結果
    //map使用
    const nums = [1,2,3,4]
    返回的結果 =  map(函數(shù))
    const res = nums.map(n => n+1);
    console.log(nums);  // [1, 2, 3, 4]
    console.log(res);  // [2, 3, 4, 5]  會創(chuàng)建新數(shù)組

    // map可以保留對象的一個特定屬性
    const obj = [
        {
            name: 'zs',
            age:12
        },
        {
            name: 'ww',
            age:33
        }
    ]
    const allName = obj.map(obj => obj.name);
    console.log(allName) // ["zs","ww"]


    // 自定義的map功能
    // myMap(數(shù)組,回調(diào)函數(shù))
    function myMap (collection,callback){
        var iterationInputs = [];
        for(var i = 0 ; i<collection.length; i++){
            iterationInputs.push(callback(collection[i]))
        }
        return iterationInputs
    }

    const res1 =  myMap(nums,n=>n+1)
    console.log(res1)

filter()

  • filter作用: 過濾數(shù)組,它接受一個函數(shù)作為唯一的參數(shù),
    • 該參數(shù)在數(shù)組的每個元素上調(diào)用,這個函數(shù)必須返回一個布爾值
    • true: 元素獎保留在數(shù)組中
    • false: 元素不會保留在數(shù)組中
    • 最終返回結果也會得到一個新數(shù)組,該數(shù)組中保留了條件為true下的元素
    • 返回數(shù)組中的偶數(shù)
    const nums = [1,2,3,4,5,6,7,8]
    const filterNums = nums.filter( n => n%2 == 0)
    console.log(nums) // [1, 2, 3, 4, 5, 6, 7, 8]
    console.log(filterNums)// [2, 4, 6, 8]

    const objArrs = [
        {
            name: 'zs',
            age:12
        },
        {
            name: 'ww',
            age:33
        },
        {
            name: 'll',
            age:22
        }
    ]
    // 移除數(shù)組中的特定某項
    function removeObj(objArrs,name){
        return objArrs.filter(obj => obj.name !== name)
    }
    console.log(removeObj(objArrs,'zs'))

    // 自定義filter()
    function myFilter(collection,callback){
        var filterArr = [];
        for (var i = 0; i< collection.length; i++){
            if(callback(collection[i])){
                filterArr.push(collection[i])
            }
        }
        return filterArr
    }

    const res = myFilter(objArrs,obj => obj.name !== 'ww')
    console.log(res);

reduce()

reduce() 方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結果匯總為單個返回值。

語法

arr.reduce(callback(accumulator, currentValue,?index,?array),[?initialValue])
  • 回調(diào)函數(shù)接受四個參數(shù)

    • accumulator 累計器累計回調(diào)的返回值; 它是上一次調(diào)用回調(diào)時返回的累積值,或initialValue
    • currentValue 數(shù)組中正在處理的元素
    • index (可選) 調(diào)用reduce()數(shù)組
    • array(可選) 調(diào)用reduce()的數(shù)組
  • 返回值

    • 函數(shù)累計處理的結果
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容