# JavaScript Array 奇技淫巧 **Published by:** [JaySong](https://paragraph.com/@coinbridge/) **Published on:** 2021-11-09 **URL:** https://paragraph.com/@coinbridge/javascript-array ## Content 1.1 求和方法一:Array.prototype.forEach()var total = 0; [1, 2, 3].forEach(function (num) { total += num; }); 复制代码 方法二:Array.prototype.reduce()var total = [1, 2, 3].reduce(function (sum, current) { return sum + current; }, 0); 复制代码 1.2 排序方法一:sort()// 默认是升序 [1, 2, 3, 4].sort((a, b) => a - b); // [1, 2, 3, 4] // 降序 [1, 2, 3, 4].sort((a, b) => b - a); // [4, 3, 2, 1] 复制代码 方法二:排序算法参考文献十大经典排序算法 - Git BookJavaScript 数据结构与算法之美 - 十大经典排序算法 - 天明夜尽1.3 取最大值方法一:Math.max()Math.max() // -Infinity,即 -∞ Math.max(Infinity, -Infinity) // Infinity,即 ∞ Math.max(...[1, 2, 3, 4]) // 4 Math.max.apply(this, [1, 2, 3, 4]) // 4 [1, 2, 3, 4].reduce( (prev, cur,curIndex,arr)=> { return Math.max(prev,cur); },0) // 4 复制代码 1.4 判断是否包含某值方法一:Array.includes()[7, 8, 9].includes(4) // false 复制代码 方法二:Array.indexOf()[7, 8, 9].indexOf(4) // -1 如果存在返回索引 [7, 8, 9].indexOf(9) // 2 复制代码 方法三:Array.find()如果数组中无值返回undefined[7, 8, 9].find((item) => item === 4) // undefined [7, 8, 9].find((item) => item === 9) // 9 复制代码 方法四:Array.findIndex()如果数组中无值返回-1[7, 8, 9].findIndex((item)=> item === 4) // -1 [7, 8, 9].findIndex((item)=> item === 9) // 2 复制代码 1.5 某一项设置值方法一:Array.splice()arr = ['aaa', 'bbbb', 'cccc', 'dddd'] arr.splice(3, 0, 3) arr // ['aaa', 'bbbb', 'cccc', 3, 'dddd'] 复制代码 1.6 每一项设置值方法一:Array.fill()[7,8,9,10,11,12].fill() // [undefined, undefined, undefined, undefined, undefined, undefined] [7,8,9,10,11,12].fill(7) // [7, 7, 7, 7, 7, 7] [7,8,9,10,11,12].fill(3, 2, 4) // [7, 8, 3, 3, 11, 12] 复制代码 方法二:Array.map()[7, 8, 9].map((item, idx) => item % 2) // [1, 0, 1] [7, 8, 9].map((item, idx) => idx) // [0, 1, 2] 复制代码 1.7 每一项是否满足方法一:Array.every()[1,2,3].every(item=>{return item>2}) //false 复制代码 1.8 有一项满足方法一:Array.some()[1,2,3].some(item=>{return item>2}) //true ## Publication Information - [JaySong](https://paragraph.com/@coinbridge/): Publication homepage - [All Posts](https://paragraph.com/@coinbridge/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@coinbridge): Subscribe to updates - [Twitter](https://twitter.com/yourboy_ss): Follow on Twitter