Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ecmascript 6 ES6模块不变性_Ecmascript 6_Vue.js_Es6 Modules - Fatal编程技术网

Ecmascript 6 ES6模块不变性

Ecmascript 6 ES6模块不变性,ecmascript-6,vue.js,es6-modules,Ecmascript 6,Vue.js,Es6 Modules,我认为ES6模块导出总是不可变的,所以我对我得到的行为感到非常困惑。我有一个简单的颜色数组,我想在Vue应用程序的多个组件中使用。它在它自己的文件中,如下所示: export const colors = [ '#ffb3ba', '#ffdfba', '#ffffba', '#bae1ff', ] 然后我将其导入到我想要使用它的组件中,如下所示: import { colors } from '../assets/colors'; 我有一个函数,用于拾取随机颜色,然后将其从

我认为ES6模块导出总是不可变的,所以我对我得到的行为感到非常困惑。我有一个简单的颜色数组,我想在Vue应用程序的多个组件中使用。它在它自己的文件中,如下所示:

export const colors = [
  '#ffb3ba',
  '#ffdfba',
  '#ffffba',
  '#bae1ff',
]
然后我将其导入到我想要使用它的组件中,如下所示:

import { colors } from '../assets/colors';
我有一个函数,用于拾取随机颜色,然后将其从列表中删除,这样就不会为同一组件再次拾取该颜色。是这样的

descriptions.forEach(item => {
      const colorIndex = Math.floor(Math.random() * colors.length);
      item['color'] = colors[colorIndex];
      colors.splice(colorIndex, 1);
    });
这里的想法是从列表中选择一种随机颜色,为其指定一个描述,然后将其从列表中删除,以便在
forEach
的下一次迭代中选择不同的颜色


问题是,它似乎要从列表中永久删除颜色。因此,当我导入并尝试在另一个组件中使用数组时,其中没有颜色。如何使每个组件都有一个新的
颜色
数组实例?

ES6模块导入不是不变的,正如您正确观察到的那样


您可以创建阵列的浅层副本并对其进行操作:

const copiedColors = [...colors];

descriptions.forEach(item => {
  const colorIndex = Math.floor(Math.random() * colors.length);
  item['color'] = copiedColors[colorIndex];
  copiedColors.splice(colorIndex, 1);
});
导入的绑定是不可分配的,仅此而已。它们类似于常量
——您无法更改变量。要防止出现这种情况,请在导出对象时冻结该对象:

export const colors = Object.freeze([
  '#ffb3ba',
  '#ffdfba',
  '#ffffba',
  '#bae1ff',
]);
如何使每个组件都有一个新的
colors
数组实例

看一下:只需
colors.slice()
。此外,您还需要了解如何有效地为您的描述获取随机颜色-甚至还有一些不改变输入的颜色

import { colors } from '../assets/colors';
import { shuffle } from '…';
const randomColors = shuffle(colors.slice());
console.assert(descriptions.length <= randomColors.length);
for (const [i, description] of descriptions.entries())
  description.color = randomColors[i];
从“../assets/colors”导入{colors};
从“…”导入{shuffle};
const randomColor=shuffle(colors.slice());

console.assert(descriptions.length制作一个克隆,这样你就有了你的列表,然后是一个可用的列表,它会根据选定或取消选定的颜色进行更新。你在导入数组时,可以修改数组中的值,但不能重新分配它的值,但我不理解你的解决方案。当我使用
Object.freeze
时,我得到一个错误:
TypeError:Cannot添加/删除密封的数组元素
。我的随机化方法有什么问题?链接的元素要复杂得多。是的,冻结只是防止删除工作的一种安全措施。您仍然需要使用
.slice()
(或
数组.from
或其他方法)制作实际副本。你的随机化方法真的很低效,重复从数组中间移除东西具有
O(n²)
复杂性。只需使用标准的Fisher-Yates随机播放(没有那么复杂)…当只有5个项目时,这真的很重要吗?我不知道Fisher-Yates shuffle的正反两面。
var currentIndex=array.length,temporaryValue,randomIndex;
我从来没有见过这样分配的变量。逗号分隔意味着什么?@MattGween只是。你可能会从更可读的地方找到代码…