网络编程 
首页 > 网络编程 > 浏览文章

9个JavaScript日常开发小技巧

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

1.生成指定范围的数字

在某些情况下,我们会创建一个处在两个数之间的数组。假设我们要判断某人的生日是否在某个范围的年份内,那么下面是实现它的一个很简单的方法

let start = 1900, end = 2000;
[...new Array(end + 1).keys()].slice(start);
// [ 1900, 1901, ..., 2000]
// 还有这种方式,但对于很的范围就不太稳定

Array.from({ length: end - start + 1 }, (_, i) => start + i);

2.使用值数组作为函数的参数

在某些情况下,我们需要将值收集到数组中,然后将其作为函数的参数传递。 使用 ES6,可以使用扩展运算符(...)并从[arg1, arg2] > (arg1, arg2)中提取数组:

const parts = {
 first: [0, 2],
 second: [1, 3],
}

["Hello", "World", "JS", "Tricks"].slice(...parts.second)
// ["World", "JS"]

3.将值用作 Math 方法的参数

当我们需要在数组中使用Math.max或Math.min来找到最大或者最小值时,我们可以像下面这样进行操作:

const elementsHeight = [...document.body.children].map(
 el => el.getBoundingClientRect().y
);
Math.max(...elementsHeight);
// 474

const numbers = [100, 100, -1000, 2000, -3000, 40000];
Math.min(...numbers);
// -3000

4.合并/展平数组中的数组

Array 有一个很好的方法,称为Array.flat,它是需要一个depth参数,表示数组嵌套的深度,默认值为1。 但是,如果我们不知道深度怎么办,则需要将其全部展平,只需将Infinity作为参数即可 "htmlcode">

const arrays = [[10], 50, [100, [2000, 3000, [40000]]]]

arrays.flat(Infinity)
// [ 10, 50, 100, 2000, 3000, 40000 ]

5. 防止代码崩溃

在代码中出现不可预测的行为是不好的,但是如果你有这种行为,你需要处理它。

例如,常见错误TypeError,试获取undefined/null等属性,就会报这个错误。

const found = [{ name: "Alex" }].find(i => i.name === 'Jim')

console.log(found.name)
// TypeError: Cannot read property 'name' of undefined

我们可以这样避免它:

const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {}

console.log(found.name)
// undefined

6. 传递参数的好方法

对于这个方法,一个很好的用例就是styled-components,在ES6中,我们可以将模板字符中作为函数的参数传递而无需使用方括号。 如果要实现格式化/转换文本的功能,这是一个很好的技巧:

const makeList = (raw) =>
 raw
  .join()
  .trim()
  .split("\n")
  .map((s, i) => `${i + 1}. ${s}`)
  .join("\n");

makeList`
Hello, World
Hello, World
`;
// 1. Hello,World
// 2. World,World

7.交换变量

使用解构赋值语法,我们可以轻松地交换变量 使用解构赋值语法 "htmlcode">

let a = "hello"
let b = "world"

// 错误的方式
a = b
b = a
// { a: 'world', b: 'world' }

// 正确的做法
[a, b] = [b, a]
// { a: 'world', b: 'hello' }

8.按字母顺序排序

需要在跨国际的项目中,对于按字典排序,一些比较特殊的语言可能会出现问题,如下所示 "htmlcode">

// 错误的做法
["a", "z", ""].sort((a, b) => a - b);
// ['a', 'z', '"a", "z", ""].sort((a, b) => a.localeCompare(b));
// [ 'a', '"htmlcode">
const password = "hackme";
password.substr(-3).padStart(password.length, "*");
// ***kme

掌握这些小技巧,在日常开发过程中可以避免很多不必要的错误,更多关于JavaScript日常开发小技巧请查看下面的相关链接

上一篇:electron踩坑之remote of undefined的解决
下一篇:详解ES6中class的实现原理
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网