这篇文章主要讲解了“JavaScript数组常用工具函数怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JavaScript数组常用工具函数怎么使用”吧!
if (!Array.isArray){ Array.isArray = function(arg){ return Object.prototype.toString.call(arg) === '[object Array]'; }; }
// 1. slice Array.prototype.slice.call(arguments) // 2. concat [].concat.apply([], arguments)
// 1. ...扩展运算符 [...arguments] // 2. Array.from() Array.from(arguments)
var a = []; // 1.基于instanceof a instanceof Array; // 2.基于constructor a.constructor === Array; // 3.基于Object.prototype.isPrototypeOf Array.prototype.isPrototypeOf(a); // 4.基于getPrototypeOf Object.getPrototypeOf(a) === Array.prototype; // 5.基于Object.prototype.toString Object.prototype.toString.call(a) === '[object Array]'; // 6. 通过Array.isArray Array.isArray(a)
Array.prototype.myForEach = function(fn, context = window){ let len = this.length for(let i = 0; i < len; i++){ typeof fn === 'function' && fn.call(context, this[i], i) } }
Array.prototype.myFilter = function(fn, context = window){ let len = this.length, result = [] for(let i = 0; i < len; i++){ if(fn.call(context, this[i], i, this)){ result.push(this[i]) } } return result }
Array.prototype.myEvery = function(fn, context){ let result = true, len = this.length for(let i = 0; i < len; i++){ result = fn.call(context, this[i], i, this) if(!result){ break } } return result }
Array.prototype.mySome = function(fn, context){ let result = false, len = this.length for(let i = 0; i < len; i++){ result = fn.call(context, this[i], i, this) if(result){ break } } return result }
Array.prototype.myFindIndex = function (callback) { for (let i = 0; i < this.length; i++) { if (callback(this[i], i)) { return i } } }
Array.prototype.myReduce = function (fn, initialValue) { let arr = Array.prototype.call(this) let res, startIndex res = initialValue ? initialValue : arr[0] startIndex = initialValue ? 0 : 1 for (let i = startIndex; i < arr.length; i++) { res = fn.call(null, res, arr[i], i, this) } return res }
let ary = [1, [2, [3, 4, 5]]]
const flatten = function(ary){ let result = [] for(let i = 0;i<ary.length;i++){ if(Array.isArray(ary[i])){ result = result.concat(flatten(ary[i])) } else { result.push(ary[i]) } } return result }
const flatten = function(ary){ return ary.reduce((prev, next)=>{ return prev.concat(Array.isArray(next) ? flatten(next) : next) }, []) }
const flatten = function(ary){ while(ary.some(item=>Array.isArray(item))){ ary = [].concat(...ary) } return ary }
const flatten = function(ary){ return ary.toString().split(',') }
const flatten = function(ary){ return ary.flat(Infinity) }
const flatten6 = function(ary){ let str = JSON.stringify(ary) str = str.replace(/([|])/g, '') return JSON.parse(`[${str}]`) }
const unique1 = (array) => { // return Array.from(new Set(array)) return [...new Set(array)] }
const unique2 = (array) => { const arr = [] const obj = {} array.forEach(item => { if (!obj.hasOwnProperty(item)) { obj[item] = true arr.push(item) } }) return arr }
const unique3 = (array) => { const arr = [] array.forEach(item => { if (arr.indexOf(item) === -1) { arr.push(item) } }) return arr }
const unique4 = (array) => { return array.filter((item,index) => { return array.indexOf(item) === index; }) }
const unique6 = (array) => { let result = []; array.forEach(item => { if(!result.includes(item)){ result.push(item); } }) return result; }
const unique6 = (array) => { let result = array.sort(function (a,b) { return a - b; }); for(let i = 0;i < result.length;i ++){ if(result[i] === result[i+1]){ result.splice(i + 1,1); i --; } } return result; }
function unique(array) { // res用来存储结果 var res = []; for (var i = 0, arrayLen = array.length; i < arrayLen; i++) { for (var j = 0, resLen = res.length; j < resLen; j++ ) { if (array[i] === res[j]) { break; } } // 如果array[i]是唯一的,那么执行完循环,j等于resLen if (j === resLen) { res.push(array[i]) } } return res; } console.log(unique(array)); // [1, "1"]
原理:利用数组的前一项与相邻的后一项相比较,判断大/小,交换位置
const bubbleSort = function(ary){ for(let i = 0; i < ary.length - 1; i++){ for(let j = 0; j < ary.length - 1 - i; j++){ if(ary[j] > ary[j+1]){ [ary[j], ary[j+1]] = [ary[j+1], ary[j]] } } } return ary }
原理:利用数组的某项与后面所有的值相比较,判断大/小,交换位置
const bubbleSort = function(ary){ for(let i = 0; i < ary.length - 1; i++){ for(let j = i + 1; j < ary.length; j++){ if(ary[i] > ary[j]){ [ary[i], ary[j]] = [ary[j], ary[i]] } } } return ary }
Array.sort((a, b)=>a-b)
原理:取数组的中间值作为基准,判断左右两边的值大或小,添加到相应数组,递归调用,然后将所有的值拼接在一起。
const quick_sort = function(ary){ if(ary.length < 1){ return ary } let centerIndex = Math.floor(ary.length/2) let centerVal = ary.splice(centerIndex, 1)[0] let left = [] let right = [] ary.forEach(item => { item > centerVal ? right.push(item) : left.push(item) }) return [...quick_sort(left), ...[centerVal], ...quick_sort(right)] }
原理:先将数组中的一项添加到新数组中,循环数组每一项与新数组中比较,比较大的值放在后面小的放到新数组的前面。
const insertion_sort = function(ary){ let newAry = ary.splice(0, 1) for(let i = 0; i < ary.length; i++){ let cur = ary[i] for(let j = newAry.length - 1; j >= 0;){ if(cur < newAry[j]){ j-- j === -1 && newAry.unshift(cur) } else { newAry.splice(j + 1, 0, cur) j = -1 } } } return [...newAry] }
const maxMin = function(ary){ let [min, max] = [ary[0], ary[1]] ary.forEach(ele => { min > ele ? min = ele : null max < ele ? max = ele : null }) return [min, max] }
var arr = [6, 4, 1, 8, 2, 11, 23]; var result = arr[0]; for (var i = 1; i < arr.length; i++) { result = Math.max(result, arr[i]); } console.log(result);
var arr = [6, 4, 1, 8, 2, 11, 23]; function max(prev, next) { return Math.max(prev, next); } console.log(arr.reduce(max));
var arr = [6, 4, 1, 8, 2, 11, 23]; arr.sort(function(a,b){return a - b;}); console.log(arr[arr.length - 1])
Math.max.apply(null, ary) // 扩展运算符 Math.max(...arr) // eval var max = eval("Math.max(" + arr + ")");
const balance = function(ary){ ary.sort((a, b) => a - b) ary.shift() ary.pop() let num = 0 ary.forEach(item => { num += item }) return (num/ary.length).toFixed(2) }
function shuffle(a) { var j, x, i; for (i = a.length; i; i--) { j = Math.floor(Math.random() * i); x = a[i - 1]; a[i - 1] = a[j]; a[j] = x; } return a; }
let arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]; Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})
感谢各位的阅读,以上就是“JavaScript数组常用工具函数怎么使用”的内容了,经过本文的学习后,相信大家对JavaScript数组常用工具函数怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。