JavaScript 数组与对象声明
数组和对象都是可变的,可以存储多个值。它们都被认为是 JavaScript 的重要组成部分。
我们将在本文中了解 JavaScript 中数组和对象声明之间的区别。
当我们存储单个变量的多个值时使用数组,而一个对象可以保存多个变量及其值。
数组也可以被视为一个对象,并具有大多数对象功能。它有一些附加功能,如 length
、pop()
、slice()
等。
要声明数组,我们将使用方括号 []
。
请参考以下代码。
var name = ["abc","def"]
console.log(name)
输出:
["abc","def"]
在上面的例子中,我们声明了一个名为 name
的数组并打印了它的内容。请注意,数组中的元素存储在特定索引处,可用于访问它们。
另一方面,一个对象让我们可以将 name
与一个值成对关联。我们可以使用键来访问对象中的值。
要声明一个对象,我们将使用大括号 {}
。
例如,
var obj = {
name: ["abc","def"],
age: 18,
}
console.log(obj.name);
console.log(obj["age"]);
输出:
["abc","def"]
18
上面的例子应该清楚了。我们创建了一个名为 obj
的对象。其中一对包含一个数组。我们能够使用它们的键访问这些元素。
相关文章
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 事件。