JavaScript 中的枚举器
枚举是 C 语言中最流行的自定义数据类型之一,它允许对整数常量进行命名,使程序易于阅读和维护。Native JavaScript 没有传统的 Enum 数据类型,而是在 TypeScript 中引入。
在今天的帖子中,我们将了解原生 JavaScript 中的枚举器。
在 JavaScript 中使用数组
创建枚举器
JavaScript 数组是具有预定义属性的特殊对象。这些是可以分配给作为输入参数传递的值的数值属性。
JavaScript 提供了几种处理数组的方法。一些最流行的数组方法是 .push()
、.pop()
、.map()
、.reverse()
等。
JavaScript 中的 indexOf
这是 JavaScript 的内置方法。此方法采用数组值并通过遍历整个数组返回索引/属性。
如果找到多个匹配值,则返回第一个匹配值索引。如果没有找到值,则返回 -1
。执行的搜索操作是使用 ===
运算符的 strict
搜索。
语法:
indexOf(searchElement)
indexOf(searchElement, fromIndex)
此方法遍历数组以查找作为输入传递的 searchElement
。我们从某个索引开始搜索,然后传递 fromIndex
。
这个 fromIndex
跳过指定索引之前的元素并从此索引开始搜索。如果此索引在数组范围之外,则返回 -1
,这意味着无法搜索该值。
有关更多信息,请阅读有关 indexOf 方法的更多信息。
const osConfig = ['Linux', 'MacOS', 'Windows', 'Ubuntu'];
console.log(osConfig.indexOf('Linux'));
在上面的示例代码中,我们定义了 OS 数组的四个值。当你传递 indexOf("Linux")
时,它将迭代 osConfig
,检查 osConfig
中的所有值。
上面代码的输出将如下所示。
输出:
0
在 JavaScript 中使用 for
循环创建一个枚举器
创建枚举的另一种方法是使用 for
循环。
用户可以创建接受输入参数的函数,并使用 for
循环遍历这些参数。然后使用每个参数创建对象,以键为参数,以值为索引或迭代次数。
function Enum() {
for (let i = 0; i < arguments.length; ++i) {
this[arguments[i]] = i;
}
return this;
}
const config = {};
config.type = new Enum('Linux', 'MacOS', 'Windows', 'Ubuntu');
console.log(config);
console.log(config.type.Linux);
在上面的例子中,我们创建了 Enum
函数,它接受参数并一个一个地迭代参数,创建本地对象。当你运行上面的代码时,你将获得以下输出。
输出:
{ type: Enum { Linux: 0, MacOS: 1, Windows: 2, Ubuntu: 3 } }
0
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。