ES6-新增的數組操作,數組解構,forEach,fillter,some.map的數組遍歷,數組轉換字符串


ES6-新增的數組操作

// es6數組格式
let json = {
    '0'  :  'anan',
    '1'  :  'anani',
    '2'  :  'anania',
    length:3
}
//es6 把數組的方法都放到了Array對象中
let arr = Array.from(json);
console.log(arr)

//Array.of方法 轉數組
// 例如后台傳的  '3,4,5,6'
let anan = Array.of(3,4,5,6,7);
console.log(anan) // 打印已轉成的數組格式


// 例如后台傳的  '[3,4,5,6]' 字符串
let anani = Array.of('ananiah','好氣啊');
console.log(anani)                   // 打印已轉成的數組格式

// find() 實例方法 (先有實例 才可以使用)  
// 可以查找 數組 也可以查找字符串 沒有值返回undefined
let zxyqswl = [1,2,3,4,5,6,7,8,9];

console.log(zxyqswl.find(function(value,index,zxyqswl){
    // value 表示當前查找的值  index 表示值得索引 數組的下標  zxyqswl 就是原型
        return value > 5;
})) //6 


//fill 使用固定值填充數組
let append  = ['anan','大誒啊','awsl'];
append.fill('wula!',0,1);  //替換第一個
append.fill('ananiah',1,2); //替換第二個
append.fill('嚶嚶嚶',2,3); //替換第三個
console.log(append)

//數組循環
for(let item of append){
    console.log(item) //循環數組的值 
}
//輸出數組下標
for(let item of append.keys()){
    console.log(item) //循環數組的下標 
}
//下標和值一起輸出
for(let [index,val] of append.entries()){
    console.log(index + ':' + val);
}

//entries  實例方法 實現 手動循環
let list  = append.entries();
console.log(list) //輸出Array Iterator數組
console.log(list.next().value) //輸出下標為0的數值
console.log(list.next().value) //輸出下標為1的數值
console.log(list.next().value) //輸出下標為2的數值 

數組解構:

//數組解構
let json1 = ['ananiah','大誒啊','web'];
function jsonarr(a,b,c){
    console.log(a,b,c) //  ananiah  大誒啊  web
}
jsonarr(...json1);

//in 的用法
let obj = {
    a:'ananiah',
    b:'大誒啊'
}
console.log('c' in obj) //false 判斷數組中是否有c

let objarr = [,,,]; //d都是空值
console.log(objarr.length) //3
console.log(0 in objarr) //false 判斷空值

數組遍歷:

//數組遍歷
let eacharr = ['anan','ananiah','false'];
eacharr.forEach((val,index) => console.log(index,val)); 
eacharr.filter(x => console.log(x)); 
eacharr.some(x => console.log(x));  //輸出的跟fillter一樣
console.log(eacharr.map(x=>'web')); //數組中的值都替換成了web

數組轉換字符串

//數組轉換字符串
console.log(eacharr.toString())
console.log(eacharr.join('|')) //字符串之間加上|  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM