前端javaScript数组常用方法

数组

数组:当你需要要生成一个0-99的数组

//方案1
const createArr = (n) => Array.from(new Array(n), (v, i) => i)
const arr = createArr(100) // 0 - 99 数组

//方案2
const createArr = (n) => new Array(n).fill(0).map((v, i) => i)
createArr(100) // 0 - 99数组

打乱数组:当你有一个数组,你需要打乱这个数组的排序

const randomSort = list => list.sort(() => Math.random() - 0.5)
randomSort([0,1,2,3,4,5,6,7,8,9]) // 随机排列结果

数组去重

//方案一
const removeDuplicates = list => [...new Set(list)]
removeDuplicates([0, 0, 2, 4, 5]) // [0,2,4,5]

//方案二

const duplicateById = list => [...list.reduce((prev, cur) => prev.set(cur.id, cur), new Map()).values()]
duplicateById([{id: 1, name: 'jack'}, {id: 2, name: 'rose'}, {id: 1, name: 'jack'}])
// [{id: 1, name: 'jack'}, {id: 2, name: 'rose'}]

多数组取交集

const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))

intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9])
// [3, 4]

查找最大值索引

//但你需要找到一个数组中的最大值的索引

const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
indexOfMax([1, 3, 9, 7, 5]); // 2

查找最小值索引

//当你需要找到一个数组中的最小值的索引

const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0)
indexOfMin([2, 5, 3, 4, 1, 0, 9]) // 5

找到最接近的数值

//当你需要在一个数组中找到一个最接近的值

const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev))
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50) // 33

压缩多个数组

//当你需要将多个数组压缩成一个数组

const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i]))
zip([1,2,3,4], ['a', 'b', 'c', 'd'], ['A', 'B', 'C', 'D'])
// [[1, 'a', 'A'], [2, 'b', 'B'], [3, 'c', 'C'], [4, 'd', 'D']]

矩阵交换行和列

//当你需要将一个矩阵的行和列进行互相交换

const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
transpose(
    [              // [
        [1, 2, 3], //      [1, 4, 7],
        [4, 5, 6], //      [2, 5, 8],
        [7, 8, 9], //      [3, 6, 9],
     ]             //  ]
 ); 

数字转换

进制转换

//将10进制转换成n进制,可以使用toString(n)

const toDecimal = (num, n = 10) => num.toString(n) 
// 假设数字10要转换成2进制
toDecimal(10, 2) // '1010'

//将n进制转换成10进制,可以使用parseInt(num, n)

const toDecimalism = (num, n = 10) => parseInt(num, n)
toDecimalism(1010, 2)

正则

手机号格式化

//当你需要将手机号码格式化成xxx-xxxx-xxxx的形式

const formatPhone = (str, sign = '-') => str.replace(/(\W|\s)/g, "").split(/^(\d{3})(\d{4})(\d{4})$/).filter(item => item).join(sign)

formatPhone('13123456789') // '131-2345-6789'
formatPhone('13 1234 56 789', ' ') // '131 2345 6789'

去除多余空格

//当你需要将一段文本中的多个空格合并成一个空格

const setTrimOut = str => str.replace(/\s\s+/g, ' ')
const str = setTrimOut('hello,   jack') // 

web

//重新加载当前页面

const reload = () => location.reload();
reload()

滚动到页面顶部

//如果你需要将页面翻到最顶部

const goToTop = () => window.scrollTo(0, 0);
goToTop()

元素滚动

如果你希望将一个元素顺滑的滚动到可视区域的起点

const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" })
scrollToTop(document.body)

如果你希望将一个元素顺滑的滚动到可视区域的终点

const scrollToBottom = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "end" })
  scrollToBottom(document.body)

检查当前是否IE浏览器

const isIE = !!document.documentMode;

从给定文本中剥离html

//当你需要在某个文本中将里面的标签全部过滤掉

const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
stripHtml('<div>test</div>') // 'test'

重定向

//当你需要跳转到其他页面

const goTo = (url) => (location.href = url);

文本粘贴

//当你需要复制文本到粘贴板上

const copy = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text)
copy('你需要粘贴的文本')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值