作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
更新:我现在明白在下面的代码中我正在改变 aggregateData
当我遍历 pagedData
时的数组.
const pagedData = [
{data: ["val1", "val2"], nextPage: 2},
{data: ["val3", "val4"], nextPage: 3},
{data: ["val5", "val6"]}
];
const aggregator = () => {
let aggregateData = [];
let hasNextPage;
let page = 1;
do {
const { data, nextPage } = pagedData[page - 1];
aggregateData = [...aggregateData, ...data];
page = nextPage;
hasNextPage = nextPage;
} while (hasNextPage);
return aggregateData;
}
console.log(aggregator());
/* output: ["val1", "val2", "val3", "val4", "val5", "val6"] */
最佳答案
不变性有时有助于减少难以捕获的错误,但这可能并不总是必需的或不是理想的情况。
什么是不变性?
不改变值是指不变性。在 JavaScript 中,array and objects are mutable .
不变性的例子:
let arr = ['John', 'Alice'];
// Adding element is mutating
arr.push('Oliver');
// Updating data is mutating
arr[1] = 'Lily'
许多其他函数可以改变这个数组。更多
here
const
不保证不变性。
const obj = {
name: 'foo'
}
// update name
obj.name = 'bar';
console.log(obj);
const arr = ['foo'];
// push new item
arr.push('bar');
console.log(arr);
let arr = ['Obito', 'Sasuke'];
let sameReferenceArray = arr;
console.log(arr === sameReferenceArray);
// here the original array did not mutate
let newArray = [...arr, 'Madara'];
console.log(arr === sameReferenceArray);
// but here it did mutate as the new array is assigned back to arr
arr = [...arr, 'Madara'];
console.log(arr === sameReferenceArray);
// simple example demostrating negative impact of mutataion
const obj = { name: "foo" };
const arr = [obj, obj]
console.log(arr);
// Mutating first element
arr[0].name = "bar";
console.log("Contents after mutation", arr);
const obj = { name: "foo" };
const arr = [{...obj}, {...obj}]
console.log(arr);
// Mutating first element
arr[0].name = "bar";
console.log("Contents after mutation", arr);
React
状态不应该被改变 (
reason )
const aggregator = () => {
let aggregateData = [];
let hasNextPage;
let page = 1;
do {
const { data, nextPage } = pagedData[page - 1];
aggregateData = [...aggregateData, ...data];
page = nextPage;
hasNextPage = nextPage;
} while (hasNextPage);
return aggregateData;
}
由于您将数据添加到数组中,因此无论如何最终都会对其进行变异。你可以做
spread
或
push
管他呢。这一切都很好,因为数组是在函数内部本地创建并返回的。
const aggregator = (aggregateData) => {
for (const i = 0; i < 5; i++)
aggregateData = [...aggregateData, i];
return aggregateData;
}
const example = () => {
let arr = [];
let data = aggregator(arr);
// if this array is passed to couple other functions too and mutated then it will get hard to track. This is where the issue can occur
}
example();
关于Javascript 不变性和本地数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68145005/
我是一名优秀的程序员,十分优秀!