ES6語法
js判斷字符串是否包含在另一個字符串中
1、舊的方式: indexOf('變量') ----> 結果為-1 代表未找到,否則就是找到了 返回下標
2、es6新增3種方式: 返回 true或false
1、includes('變量',搜索的位置) 表示是否找到參數變量
2、startsWith('變量',搜索的位置) 從頭部匹配
3、endsWith('變量',搜索的位置) 從尾部匹配
str.repeat(n) 表示將源字符串重復n次
‘hello’.repeat(3) ---> 'hellohellohello'
參數如果是小數,會被取整
參數如果是負數或者infinity,會報錯
str.padStart(最小長度,補全的字符串) 表示頭部補全最小長度的字符串
str.padEnd(最小長度,補全的字符串) 表示尾部補全最小長度的字符串
示例:‘920312’.padEnd(10,'0') ---> '9203120000' tip:必須是字符串
函數、
//1、需求:篩選出數組中數字小於100的數字。 //2、需求:將數組中的每個數字乘以3. //3、需求:數組中的數組匯總求和。 let nums = [16,38,49,88,291,32,231,123,101,22] //舊的寫法: let old_newnums = [] //[16, 38, 49, 88, 32, 22] //1、 for (let i = 0; i < nums.length; i++) { if (nums[i]<100) {old_newnums.push(nums[i])} } //2、 let old_newnums1 = [] //[48, 114, 147, 264, 96, 66] for (let i = 0; i < old_newnums.length; i++) { old_newnums1.push(old_newnums[i]*3) } //3、 let old_newnums2 = 0 // 735 for (let i = 0; i < old_newnums1.length; i++) { old_newnums2 += old_newnums1[i] } //新的寫法: filter / map / reduce // filter中的回調函數有一個要求:必須返回一個bollean值 // true : 當返回true時,函數內部會自動將這次回調的n加入到新的數組中 // false: 當返回fasle時,函數內部會過濾掉這次的n。 let new_nums = nums.filter(function (n) { return n < 100 }) // map 映射函數 let new_nums1 = new_nums.map(function (n) { return n * 3 }) // reduce(func(上一次結果 初始值為默認值,數組的n),默認值=0) 對數組中所有的內容進行匯總。 let new_nums2 = new_nums1.reduce(function (prev,n){ return prev + n },0) //或者可以寫成 let new_writeNums = nums.filter(function (n){return n < 100}).map(function(n){return n * 3}).reduce(function(prev,n){return prev + n},0)