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 ~

有不对的地方还望大神指点一二

 

最新文章

  1. [异常解决] How make ubuntu use Google Search
  2. cvs update后输出的文件标志 和 update常用的几个参数
  3. js的几种数据类型
  4. 双核CPU,跑程序会报rcu_sched_state detected stalls on CPUs/tasks 错误
  5. Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError
  6. sqlserver 作业调度(作业常用的几个步骤)
  7. Embeding Python &amp; Extending Python with FFPython
  8. mysql 修改字符集
  9. C# 实现:将一个文件夹下的.png图片全部移动到另一个文件夹
  10. C#实现Ruby的负数索引器
  11. SelectSort 选择排序
  12. 【stm32】ADC的规则通道和注入通道混合使用
  13. P4177 [CEOI2008]order 网络流,最小割,最大权闭合子图
  14. PHP二维数组按照键值排序
  15. php 中输入输出提交
  16. Django之基于iframe的ajax伪造
  17. html5&lt;embed&gt;的完整属性
  18. 对ubuntu初学感想
  19. KEIL C51代码优化详细分析
  20. HttpServletRequest的随手记

热门文章

  1. LightOJ1094 - Farthest Nodes in a Tree(树的直径)
  2. 转:TLV 格式及编解码示例
  3. DTrace C++ Mysteries Solved 转
  4. 公布Java桌面程序
  5. Codeforces Round #135 (Div. 2)---A. k-String
  6. SGU - 311 Ice-cream Tycoon(线段树)
  7. Hibernate之三态篇
  8. Eclipse:Some sites could not be found. See the error log for more detail.解决的方法
  9. [转] When to use what language and why
  10. HDU 4277 USACO ORZ(暴力+双向枚举)