一行Javascript代码系列

69 阅读1分钟

1、获取数组中的随机元素

使用 Math.random() 函数和数组长度可以轻松获取数组中的随机元素:

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

2、数组扁平化

使用 reduce() 函数和 concat() 函数可以轻松实现数组扁平化:

const arr = [[1, 2], [3, 4], [5, 6]];
const flattenedArr = arr.reduce((acc, cur) => acc.concat(cur), []);
console.log(flattenedArr); // [1, 2, 3, 4, 5, 6]

3、对象数组根据某个属性值进行排序

const sortedArray = array.sort((a, b) => (a.property > b.property ? 1 : -1));

4、从数组中删除特定元素

const removedArray = array.filter((item) => item !== elementToRemove);

5、检查数组中是否存在重复项

const hasDuplicates = (array) => new Set(array).size !== array.length;

6、判断数组是否包含某个值

const hasValue = arr.includes(value);

7、首字母大写

const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

8、获取随机整数

const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;

9、获取随机字符串

const randomStr = Math.random().toString(36).substring(2, length);

10、使用解构和 rest 运算符交换变量的值:

let a = 1, b = 2
  [b, a] = [a, b]
console.log(a, b) // 2, 1

11、将字符串转换为小驼峰式命名:

const str = 'hello world'
const camelCase = str.replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, '').replace(/^(.)/, ($1) => $1.toLowerCase())
console.log(camelCase) // "helloWorld"

12、计算两个日期之间的间隔

const diffInDays = (dateA, dateB) => Math.floor((dateB - dateA) / (1000 * 60 * 60 * 24));

13、查找日期位于一年中的第几天

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

14、复制内容到剪切板

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");

15、获取变量的类型

const getType = (variable) => Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();

getType('');     // string
getType(0);      // number
getType();       // undefined
getType(null);   // null
getType({});     // object
getType([]);     // array
getType(0);      // number
getType(() => {});  // function

16、检测对象是否为空

const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor

17判断两个数组相同元素、不同key对应的值不同进行赋值

const updatedArray1 = state.contractGoodsData.map(contractItem => {
    const goods = state.contractGoodsShowData.find(goodsItem => goodsItem.goods_id === contractItem.goods_id);
    if (goods && (contractItem.supply_price != goods.supply_price || contractItem.model_price != goods.model_price || contractItem.is_rebate != goods.is_rebate) ) {
      return { ...contractItem, supply_price: goods.supply_price, model_price: goods.model_price, is_rebate: goods.is_rebate };
    }
    return contractItem;
  });