javascript常用方法

map():遍历数组并对每个元素进行处理,返回一个新数组。

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
// doubled: [2, 4, 6, 8]

filter():遍历数组并根据条件筛选元素,返回一个新数组。

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(number => number % 2 === 0);
// evens: [2, 4]

reduce():遍历数组并将每个元素累积到一个值,返回累积值。

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// sum: 10

forEach():遍历数组并对每个元素执行回调函数,无返回值。

const numbers = [1, 2, 3, 4];
numbers.forEach(number => console.log(number));

some():判断数组中是否有元素满足指定条件,返回布尔值。

const numbers = [1, 2, 3, 4];
const hasOdd = numbers.some(number => number % 2 === 1);
// hasOdd: true

every():判断数组中所有元素是否都满足指定条件,返回布尔值。

const numbers = [1, 2, 3, 4];
const allPositive = numbers.every(number => number > 0);
// allPositive: true

对象处理方法
Object.keys():返回一个包含对象所有属性名的数组。

const person = { name: 'Alice', age: 30 };
const keys = Object.keys(person);
// keys: ['name', 'age']

Object.values():返回一个包含对象所有属性值的数组。

const person = { name: 'Alice', age: 30 };
const values = Object.values(person);
// values: ['Alice', 30]

Object.entries():返回一个包含对象所有 [key, value] 对的二维数组。

const person = { name: 'Alice', age: 30 };
const entries = Object.entries(person);
// entries: [['name', 'Alice'], ['age', 30]]

Object.assign():将一个或多个对象的属性合并到目标对象。

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = Object.assign({}, obj1, obj2);
// merged: { a: 1, b: 3, c: 4 }

字符串处理方法

split():将字符串按照指定分隔符分割成数组。

const str = 'hello,world';
const arr = str.split(',');
// arr: ['hello', 'world']

join():将数组中的元素按照指定分隔符连接成字符串。

const arr = ['hello', 'world'];
const str = arr.join(' ');
// str: 'hello world'

replace():替换字符串中匹配到的子串。

const str = 'hello,world';
const newStr = str.replace(',', ' ');
// newStr: 'hello world'

slice():提取字符串的一部分。

const str = 'hello,world';
const subStr = str.slice(0, 5);
// subStr: 'hello'

indexOf():查找子串在字符串中首次出现的位置。

const str = 'hello,world';
const position = str.indexOf('world');
// position: 6

数值处理方法

parseInt():将字符串解析为整数

const str = '42';
const num = parseInt(str, 10);
// num: 42

parseFloat():将字符串解析为浮点数。

const str = '3.14';
const num = parseFloat(str);
// num: 3.14

toFixed():将数值保留指定位数的小数。

const num = 3.14159;
const fixedNum = num.toFixed(2);
// fixedNum: '3.14'

Math.floor():向下取整。

const num = 3.9;
const integer = Math.floor(num);
// integer: 3

Math.ceil():向上取整。

const num = 3.1;
const integer = Math.ceil(num);
// integer: 4

日期处理方法

Date.now():获取当前时间的毫秒数。

const now = Date.now();

Date.parse():解析日期字符串为毫秒数。

const dateString = '2021-09-01';
const timestamp = Date.parse(dateString);

getFullYear()、getMonth()、getDate() 等:获取日期的年份、月份、日期等信息。

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();

setFullYear()、setMonth()、setDate() 等:设置日期的年份、月份、日期等信息。

const date = new Date();
date.setFullYear(2022);
date.setMonth(0); // 设置月份为 1 月
date.setDate(1);

Map

Map 是一种特殊的数据结构,可以通过键值对存储数据。

创建 Map

const myMap = new Map([
  ['a', 1],
  ['b', 2],
]);
// myMap: Map(2) {"a" => 1, "b" => 2}

获取值

myMap.get('a'); // 1

设置值

myMap.set('c', 3);
// myMap: Map(3) {"a" => 1, "b" => 2, "c" => 3}

删除键值对

myMap.delete('a');
// myMap: Map(2) {"b" => 2, "c" => 3}

其他方法

setTimeout():延迟执行函数。

setTimeout(() => {
  console.log('Hello, world');
}, 1000); // 延迟 1 秒后输出 'Hello, world'

setInterval():定时执行函数。

setInterval(() => {
  console.log('Hello, world');
}, 1000); // 每隔 1 秒输出 'Hello, world'

clearTimeout() 和 clearInterval():取消延迟执行或定时执行的函数。

const timeoutId = setTimeout(() => {
  console.log('Hello, world');
}, 1000);
clearTimeout(timeoutId); // 取消延迟执行函数
const intervalId = setInterval(() => {
  console.log('Hello, world');
}, 1000);
clearInterval(intervalId); // 取消定时执行函数

1、 javascript 中数组对象求交集、并集、补集

  • 交集
 const c = a.filter( a => b.some(b => b.categoryId  === a.categoryId))
  • 补集(差集)
const d = a.filter(x => b.every(y => y.categoryId !== x.categoryId))
  • 并集
const e = b.filter(y => a.every(x => x.categoryId !== y.categoryId)).concat(a)

2、输入框非空的判断

在处理输入框相关业务时,往往会判断输入框未输入值的场景。

if(value !== null && value !== undefined && value !== ''){
    //...
}

ES6中新出的空值合并运算符了解过吗,要写那么多条件吗?

if((value??'') !== ''){
  //...
}

3、关于获取对象属性值的吐槽

const name = obj && obj.name;

ES6中的可选链操作符

const name = obj?.name;

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

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

5.数组扁平化

使用 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]

6.对象数组根据某个属性值进行排序

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

7.从数组中删除特定元素

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

8.检查数组中是否存在重复项

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

9.判断数组是否包含某个值

const hasValue = arr.includes(value);

10.首字母大写

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

11.获取随机整数

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

12.获取随机字符串

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

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

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

14.将字符串转换为小驼峰式命名:

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

15.计算两个日期之间的间隔

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

16.查找日期位于一年中的第几天

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

17.复制内容到剪切板

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

copyToClipboard("Hello World");

18.获取变量的类型

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

19.检测对象是否为空

const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值