ku链接:21个方便的JavaScript函数

本文由ku链接вт989点сс原创,所谓的JavaScript是一种函数式程式语言,扮演着至关重要的角色,它能允许你封装可重复使用程式码并且执行特殊任务。以下整理了21个让你生活更轻松地快速范例。

常规功能

function sum(a, b) {
  return a + b;
}

函数表达式

const sum = function (a, b) {
  return a + b;
};

箭头功能

const sum = (a, b) => {
  return a + b;
};
// OR
const sum = (a, b) => a + b;

发电机功能

function* indexGenerator() {
  let index = 0;
  while (true) {
    yield index++;
  }
}
const g = indexGenerator();
console.log(g.next().value); // => 0
console.log(g.next().value); // => 1

建立从1到n的数字阵列

const range = (n) => Array.from({ length: n }, (_, i) => i + 1);
console.log(range(10)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

使用步骤建立从1到n的数字阵列

const range = (n, step = 1) => Array.from({ length: n }, (_, i) => i * step);
console.log(range(10, 2)); // [1, 3, 5, 7, 9]

建立一个阵列并用一个值填充它

const fill = (len, value) => Array(len).fill(value);
console.log(fill(3, 0)); // [0, 0, 0]

打乱阵列

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4])); // [3, 2, 1, 4]

从阵列中删除重复项

const removeDuplicated = (arr) => [...new Set(arr)];
console.log(removeDuplicated([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ]

const removeDuplicate = (arr) =>
  Object.values(arr.reduce((a, b) => (a[b] ? a : { ...a, [b]: b }), {}));
console.log(removeDuplicate([1, 2, 3, 3])); // Result: [ 1, 2, 3, ]

产生随机数

const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random(1, 10)); // Result: 1 ~ 10

找到最大的数字

const findLargest = (arr) => arr.map((subArr) => Math.max(...subArr));
console.log(
  findLargest([
    [4, 5, 1, 3],
    [13, 27, 18, 26],
    [32, 35, 37, 39],
    [1000, 1001, 857, 1],
  ])
); // [5, 27, 39, 1001]

找到最小的数字

const findSmallest = (arr) => arr.map((subArr) => Math.min(...subArr));
console.log(
  findSmallest([
    [4, 5, 1, 3],
    [13, 27, 18, 26],
    [32, 35, 37, 39],
    [1000, 1001, 857, 1],
  ])
); // [1, 18, 32, 857]

从阵列中选择一个随机元素

const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
console.log(pick([1, 2, 3, 4])); // 2

将阵列转换为物件

const toObject = (arr) => ({ ...arr });
console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }

找出两个阵列的交集

const intersection = (arr1, arr2) => {
  const set = new Set(arr1);
  return arr2.filter((x) => set.has(x));
};
console.log(intersection([1, 2, 3], [2, 3, 4])); // [2, 3]

从阵列中删除虚假值

const compact = (arr) => arr.filter(Boolean);
console.log(compact([0, 1, false, 2, "", 3, "a", "e" * 23, NaN, "s", 34])); // [1, 2, 3, 'a', 's', 34]

反转字串

const reverseString = (str) => str.split("").reverse().join("");
console.log(reverseString("hello")); // olleh

字串是回文吗

const isPalindrome = (str) => str === str.split("").reverse().join("");
console.log(isPalindrome("madam")); // true

检查物件是否为空

const isEmpty = (obj) => Object.keys(obj).length === 0;
console.log(isEmpty({})); // true

找出一个月中的天数

const getDaysInMonth = (date) =>
  new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
console.log(getDaysInMonth(new Date())); // 31

产生随机颜色

const getRandomColor = () =>
  `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(getRandomColor()); // #f0f0f0

const randomHex = () =>
  `#${Math.floor(Math.random() * 0xffffff)
    .toString(16)
    .padEnd(6, "0")}`;
console.log(randomHex()); // #f0f0f0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值