编写 JavaScript 的另一种方法

2025-06-10

编写 JavaScript 的另一种方法

最初发表在我的博客上

大家好,在这篇文章中,我将与大家分享一些前端代码,我们可以用另一种方式编写它,
而且一切运行良好,不会破坏规则或在代码中产生异味,很酷。

1. 生成一个连续的数字数组[1, 2, 3, ...., n]

如果我们想生成这样的数组,我们可以使用with[1, 2, 3, 4, 5, 6, ...., n]编写代码,这样它就会new Array()
Array.fill()

const N = 10;
new Array(N).fill().map((_, indx) => indx + 1); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

为什么new Array(N).map()不工作?

很酷,但如果我们要处理一个包含大量连续数字的数组,这种方法会是最好的吗?
嗯,不会!因为它new Array()会创建一个空洞数组
,比压缩数组
慢得多。所以我们可以避免这种情况, 用 以下代码重写此方法:Array.from()

const N = 10;
Array.from({ length: N }, (_, indx) => indx + 1); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

新数组()
来源:https://slidrio-decks.global.ssl.fastly.net/1259/original.pdf? 1521622174 幻灯片:102

您可以在 Chrome 控制台中检查这个空数组,因此如果我们写入此内容,new Array(10)您的控制台将显示
[empty × 10]一个空值数组。

更多资源:

  1. https://v8.dev/blog/elements-kinds
  2. https://stackoverflow.com/questions/3746725/how-to-create-an-array-making-1-n

2. 数字格式

EGP 1000有时你想用特定的货币或某种东西的大小来表示 money 50 kB,其中一种写法就是
简单的const money = '1000 EGP'。但有一种更好的方法是使用 来格式化数字Intl.NumberFormat。所以这个字符串将是

const money = new Intl.NumberFormat("en", {
  style: "currency",
  currency: "EGP",
  useGrouping: false,
  maximumSignificantDigits: 1
}).format(1000);
// "EGP 1000"

const storage = new Intl.NumberFormat("en", {
  style: "unit",
  unit: "kilobyte"
}).format(50);
// "50 kB"
Enter fullscreen mode Exit fullscreen mode

注意:样式units适用于 Chrome 77 及以上版本,因此您可以使用 Babel 进行编译。

如果您正在处理多个语言环境,并希望以更佳且完全自定义的方式在它们之间切换,那么这非常实用。
更多信息请访问V8 博客:Intl.NumberFormat

3. 为非交互元素添加焦点样式

tabindex根据MDN的说法,你不能使用 css/html 来做到这一点

避免将该tabindex属性与非交互式内容结合使用,以使原本旨在进行交互式操作的内容能够通过键盘输入获得焦点。例如,使用元素<div>来描述按钮,而不是使用<button>元素本身。

并且 w3 说:

应该使用交互元素( <a>、、、、、等)语义地描述内容<button><details><input><select><textarea>

因此,最佳做法是使用addEventListener()JavaScript但如果您想使用,tabindex请不要忘记添加tabindex到内部 html 内容。

另一种解决方案

tabindex如果您只是想更改边框,则不必使用div
您可以使用:focus-within并仅更改边框。

.search-box {
  margin-left: 1%;
  outline: red;
  border: 1px solid #fc3;
}

.search-input {
  border: none;
}

.search-input:focus {
  outline: none;
}

.search-box:focus-within {
  border: 2px solid #53c9fc;
}
Enter fullscreen mode Exit fullscreen mode
<div class="search-box">
  <Row>
    <div class="search-box-icon"></div>
    <input class="search-input" placeholder="search in listbox" />
  </Row>
</div>
Enter fullscreen mode Exit fullscreen mode

我在 stackoverflow 上发布了这个答案

最后,我相信我们每个人都有一种编写代码的风格,一种自己喜欢的做法,那就是不破坏规则,
也不在代码中留下异味。

鏂囩珷鏉ユ簮锛�https://dev.to/zeyadetman/another-way-to-write-your-javascript-nch
PREV
如何在 WordPress 主题中添加 React
NEXT
自托管 PaaS 的兴起——您只需要 5 美元的 VPS 吗?