JavaScript 數組常用方法(二)

  1. 如何截取數組中指定範圍內容
  2. 如何查找元素在數組中的位置
  3. 如何判斷數組中是否包含某個元素
  4. 如何把字符串轉換爲數組

 

如何截取數組中指定範圍內容

arr.slice(1, 3)

    let arr = [1, 3, 5, 7, 9];
    let res = arr.slice(1, 3);
    console.log(arr);   //[1, 3, 5, 7, 9]
    console.log(res);   //[3, 5];

slice注意點:
slice是包頭不包尾的一個方法,意思就是他截取的時候,他只包含參數1,而不包含參數2;
slice 參數1 = 開始位置
slice 參數2 = 結束位置
slice 不改變原數組,而且會返回一個新數組

 

如何查找元素在數組中的位置

arr.indexOf()

如果indexOf查找到元素

    let arr = [1, 3, 5, 7, 9];
    let res = arr.indexOf(3);
    console.log(res);   //[1] 返回下標

如果indexOf沒有查找到元素

    let arr = [1, 3, 5, 7, 9];
    let res = arr.indexOf(0);
    console.log(res);   //[-1] 返回下標

如果數組中有兩個一樣的數據,我想查找第二個(默認從左至右查找,找到就返回)

    let arr = [1, 3, 5, 7, 9, 3];
    let res = arr.indexOf(3);
    console.log(res);   //[1] 返回下標

而如果我一定要使用indexOf查找到第二個,那麼則需要用到indexOf的第二個參數

    let arr = [1, 3, 5, 7, 9, 3];
    let res = arr.indexOf(3,2);
    console.log(res);   //[5] 返回下標

indexOf 注意點 :
indexOf 參數 :
indexOf 參數1 = 需要查找的元素
indexOf 參數1 = 從第幾個下標開始找起
indexOf 返回值 :
indexOf 如果找到了元素 = 返回找到元素的下標
indexOf 如果沒有找到元素 = 返回 - 1

 

arr.lastIndexOf()

    let arr = [1, 3, 5, 7, 9];
    let res = arr.lastIndexOf(3);
    console.log(res);   //[1] 返回下標

lastIndexOf 使用方法和注意點是indexOf一樣 ,唯一區別就是:
indexOf 是從左往右開始查找
lastIndexOf 是從右往左開始查找

 

如何判斷數組中是否包含某個元素

indexOf 和 lastIndexOf

    let arr = [1, 3, 5, 7, 9];
    let res = arr.indexOf(3);
    console.log(res);   // 1
    let arr = [1, 3, 5, 7, 9];
    let res = arr.lastIndexOf(3);
    console.log(res);   // 1
    let arr = [1, 3, 5, 7, 9];
    let res = arr.indexOf(0);
    console.log(res);    //-1
    let arr = [1, 3, 5, 7, 9];
    let res = arr.lastIndexOf(0);
    console.log(res);   //-1

使用 indexOflastIndexOf,查找數組,如果有該元素就返回 下標, 如果沒有該元素就返回 -1

 

arr.includes()

    let arr = [1, 3, 5, 7, 9];
    let res = arr.includes(1);
    console.log(res);  //true
    let arr = [1, 3, 5, 7, 9];
    let res = arr.includes(0);
    console.log(res);  //fasle

使用 arr.includes()進行查找數組中是否有這個元素,如果有 ,返回true,如果沒有.返回false

 

如何把字符串轉換爲數組

split()

    let str = "1,3,5,7,9";
    let arr = str.split(",");
    console.log(arr); //["1", "3", "5", "7", "9"]

split方法和join方法正好是相反的,split是把字符串轉數組,join是把數組轉字符串,兩種方法都是通過參數來進行分割

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章