在 JavaScript 中创建字典并添加键值对
本文介绍了如何在 JavaScript 中创建字典并向其中添加键值对。
截至目前,JavaScript 不包含本机字典数据类型。
但是,JavaScript 中的对象用途广泛,可能会生成键值对。这些东西与字典非常相似,并且操作相似。
经常使用字典,因为保存的每个值都有一个唯一的键,并且使用这些键,可以检索它们的关联值。它为读取和存储数据提供了很大的自由度。
在 JavaScript 中使用对象文字创建字典
可以使用两种方式生成字典。对象字面量方法使用 new
关键字。
但是,我们专注于前者。
这是因为你以前很可能使用过字典,并且这种方法遵循熟悉的语法。
使用 Object 字面量的语法:
使用下面的语法生成一个空的 JavaScript 字典,其中 dict
是对象的名称。
var dict = {};
初始化和构造字典:
var dict = {
Name: 'Shiv',
Age: 21,
Job: 'Freelancer',
Skills: 'JavaScript',
};
console.log(dict);
输出:
{
Age: 21,
Job: "Freelancer",
Name: "Shiv",
Skills: "JavaScript"
}
在此处运行代码。
在 JavaScript 中添加键值对
构建 JavaScript 字典时可以添加键值对;但是,这些技术也可以添加值。
添加项目的代码:
var [key] = value;
key
代表唯一键的标识符,value
是键相关的对应数据。
如果字典已经包含你作为键提供的名称,你可以更改键或使用以下代码更新值。
dict.key = new_value;
访问事物同样是相当基本的;可以使用以下代码。
var value = dict.key;
值
与你用来保存访问键值的变量有关。
例子:
<!DOCTYPE html>
<html>
<head>
<title>Dictionary in Javascript</title>
</head>
<body style="text-align: center;">
<h1>Dictionary in Javascript</h1>
<p>
var dict = { <br />
"key_1" : 1 , <br />
"key_2" : "2", <br />
"key_3" : 3 <br />
}; <br />
</p>
<button onClick="funcn()">Add new Key-Value Pairs</button>
<p id="demo"></p>
<!-- Script to create dictionary
and add key-value pairs -->
<script>
function funcn() {
var dict = {
key_1: 1,
key_2: "2",
key_3: 3,
};
dict.new_key = "new_value";
dict["another_new_key"] = "another_value";
var to_show = "var dict = { <br>";
for (var key in dict) {
to_show += '"' + key + '" : ' + dict[key] + "<br>";
}
to_show += " }; <br>";
document.getElementById("demo").innerHTML = to_show;
}
</script>
</body>
</html>
在此处运行代码。
输出:
相关文章
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 事件。