function updateArrayByIndexAndKey(array, index, key, newValue) {
// 创建数组的副本以避免直接修改原数组
const newArray = [...array];
// 检查给定的索引是否在数组范围内
if (index >= 0 && index < newArray.length) {
// 修改指定索引处对象的指定键的值
newArray[index][key] = newValue;
} else {
console.warn(`警告:索引${index}超出数组范围。`);
}
return newArray;
}
// 示例
let a = [{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}];
let newIndexValue = 20;
let updatedArray = updateArrayByIndexAndKey(a, 0, 'b', newIndexValue);
console.log(updatedArray); // 输出:[{"a": 1, "b": 20}, {"a": 3, "b": 4}, {"a": 5, "b": 6}]
这个函数接收四个参数:原始数组、要修改元素的索引、要修改的键名以及新值。它首先创建了一个原数组的浅拷贝以保护原数据不受影响,然后检查提供的索引是否有效。如果索引有效,它会更新对应位置对象中指定键的值,最后返回修改后的新数组。
本文暂时没有评论,来添加一个吧(●'◡'●)