5 分钟掌握 JS 实用窍门技巧,帮你快速撸码--- 删除数组尾部元素、E6对象解构、async/await、 操作平铺嵌套多维数组等
2024-10-19 14:55:40
1. 删除数组尾部元素
一个简单方法就是改变数组的length
值:
const arr = [11, 22, 33, 44, 55, 66];
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
arr.length = 0;
console.log(arr); //=> []
2. 使用对象解构
let data = {
message:"messages",
title:"titles",
} let { message, title } = data;
console.log(message, title); let { message:messages, title:titles } = data;
console.log(messages, titles);
3. 在 Switch 语句中使用范围值
function getWaterState(tempInCelsius) {
let state;
switch (true) {
case tempInCelsius <= 0:
state = "Solid";
break;
case tempInCelsius > 0 && tempInCelsius < 100:
state = "Liquid";
break;
default:
state = "Gas";
}
return state;
}
4. await 多个 async 函数
在使用 async/await 的时候,可以使用 Promise.all 来 await 多个 async 函数
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
5. 从数组中移除重复元素
通过使用集合语法和 Spread 操作,可以很容易将重复的元素移除:
const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]
6. 平铺多维数组
使用 Spread 操作平铺嵌套多维数组:
const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(...arr);
//=> [11, 22, 33, 44, 55, 66]
希望这些小技巧能帮助你写好 JS ~
有不对的地方还望大神指点一二
最新文章
- [异常解决] How make ubuntu use Google Search
- cvs update后输出的文件标志 和 update常用的几个参数
- js的几种数据类型
- 双核CPU,跑程序会报rcu_sched_state detected stalls on CPUs/tasks 错误
- Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError
- sqlserver 作业调度(作业常用的几个步骤)
- Embeding Python &; Extending Python with FFPython
- mysql 修改字符集
- C# 实现:将一个文件夹下的.png图片全部移动到另一个文件夹
- C#实现Ruby的负数索引器
- SelectSort 选择排序
- 【stm32】ADC的规则通道和注入通道混合使用
- P4177 [CEOI2008]order 网络流,最小割,最大权闭合子图
- PHP二维数组按照键值排序
- php 中输入输出提交
- Django之基于iframe的ajax伪造
- html5<;embed>;的完整属性
- 对ubuntu初学感想
- KEIL C51代码优化详细分析
- HttpServletRequest的随手记
热门文章
- LightOJ1094 - Farthest Nodes in a Tree(树的直径)
- 转:TLV 格式及编解码示例
- DTrace C++ Mysteries Solved 转
- 公布Java桌面程序
- Codeforces Round #135 (Div. 2)---A. k-String
- SGU - 311 Ice-cream Tycoon(线段树)
- Hibernate之三态篇
- Eclipse:Some sites could not be found. See the error log for more detail.解决的方法
- [转] When to use what language and why
- HDU 4277 USACO ORZ(暴力+双向枚举)