// 擴展運算符 const fue = ['agg','apple','origen'] console.log(...fue) // for of const arr = ['a','b','c','d'] const obj = [{name:'a'},{name:'b'},{name:"c"}] for (item of arr){ console.log(item) } for(item of obj){ console.log(item.name) } //includes() 查找數組中是否存在某一項,區分大小寫,返回布爾值 const garge = ['BMV','ALN','KKk'] console.log(garge.includes('BMV')) //some()方法檢查在數組中是否存在某些元素,若是存在返回true,不然返回false。這和includes()方法類似,可是some()方法的參數是一個函數,而不是一個字符串。 const obj2 = [{name:'zhangsan',age:3},{name:'lisi',age:4},{name:'wnagwu',age:5}] console.log(obj2.some(item => item.age>=4)) //every()方法循環遍歷數組,檢查數組中的每一個元素項,並返回true或false。與some()概念類似。可是每一項都必須經過條件表達式,不然返回false。 const obj3 = [{name:'zhangsan',age:3},{name:'lisi',age:4},{name:'wnagwu',age:5}] console.log(obj3.every(item => item.age>=4)) //filter()方法建立一個包含全部經過測試的元素的新數組。 const prices=[25,30,15,55,40,10]; console.log(prices.filter((price)=>price>=30)); //map() 在返回新數組方面,map()方法跟filter()方法類似。可是,惟一的區別是它用於修改數組中的元素項。 const arr2 = [1,2,3,4] console.log(arr2.map(item => item*10)) // reduce()方法可用於將數組轉換爲其餘內容,能夠是整數,對象,promises 鏈(順序執行的promises)等等。 // 出於實際緣由,一個簡單的用例是對整數列表求和。簡而言之,它將整個數組「縮短」爲一個你想要的值。 const week=[200,350,1500,5000,450,680,350] console.log(week.reduce((first,last)=>first+last)) var result = [ { subject: 'math', score: 10 }, { subject: 'chinese', score: 20 }, { subject: 'english', score: 30 } ]; var sum = result.reduce(function(prev, cur) { return cur.score + prev; }, 0); console.log(sum) //60
幾種經常使用的方法數組