JavaScript 如何更新数组中的对象
数组是 JavaScript 中具有固定数字键和动态值的对象,可以在单个变量中包含任意数量的数据。数组可以是一维或多维的。JavaScript 数组可以直接存储值,也可以存储 JavaScript 对象。与其他语言不同,JS 数组可以在同一数组的不同索引处包含不同的数据类型。
在今天的帖子中,我们将了解如何在 JavaScript 中更新数组的对象。
JavaScript 提供了两种更新对象的方法,使用 map()
和 findIndex()
。
这个由 JavaScript 提供的内置数组方法遍历原始数组并创建新数组,根据指定的条件完成元素。除了箭头函数,你还可以传递回调函数。map()
和 forEach()
之间的唯一区别是 map()
将创建新数组,而 forEach()
会改变原始数组。
Array.prototype.map(element => $updateCondition);
Array.prototype.map($callbackFn);
$updateCondition
:这个强制性参数指定应该为每个元素执行哪个操作。
$callbackFn
:它是一个强制参数,它为要调用的数组的每个元素指定一个函数。每次调用该函数时,它都会将结果返回到新数组。
返回新数组,其中元素是回调函数的结果。
示例代码:
const osArray = [
{id: 0, name: "Windows"},
{id: 1, name: "Linux"},
{id: 2, name: "MacOS"},
];
const updatedOSArray = osArray.map(p =>
p.id === 1
? { ...p, name: 'Ubuntu' }
: p
);
console.log("After update: ", updatedOSArray);
输出:
After update: [
{id: 0, name: "Windows"},
{id: 1, name: "Ubuntu"},
{id: 2, name: "MacOS"}
]
这个内置的数组方法由 JavaScript 提供,它会查找值与指定条件匹配的元素的索引。除了箭头函数,你还可以传递回调函数。findIndex()
和 indexOf()
这两种方法之间只有一个区别。findIndex()
用于复杂的匹配条件或对象数据类型,而 indexOf()
用于简单条件或原始数据类型。
Array.prototype.findIndex(element => $condition);
Array.prototype.findIndex($callbackFn);
$condition
:这是一个强制性参数。用户可以传递与数组元素相关的任何条件,并找到第一个满足条件的匹配元素。
返回满足指定条件的数字索引。如果没有元素满足指定条件,则返回 -1
。
示例代码:
const osArray = [
{id: 0, name: "Windows"},
{id: 1, name: "Linux"},
{id: 2, name: "MacOS"},
];
elementIndex = osArray.findIndex((obj => obj.id == 1));
console.log("Before update: ", osArray[elementIndex]);
osArray[elementIndex].name = "Ubuntu";
console.log("After update: ", osArray[elementIndex]);
输出:
Before update: {id: 1, name: 'Linux'}
After update: {id: 1, name: 'Ubuntu'}
相关文章
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 事件。