javascript - 如何覆盖文件对象值?
问题描述
我有一个函数,它基本上从数组中获取一个文件对象,并通过一些调整来复制它:
i
是数组索引
duplicate(i) {
const arr = [...this.state.files];
console.log(arr[i].color) //red
let name = arr[i].name.slice(0, -4);
name = `${name}-${Math.floor(Math.random() * 1000) + 1}.png`;
const newFile = new File([""],name)
const index = i + 1;
arr.splice(index, 0, newFile)
arr[i+1].id = Math.random().toString(32);
arr[i+1].color = arr[i].color //set the color to red
arr[i+1].preview = arr[i].preview;
console.log(arr[i+1]) //color in arr is now black (the default color)
this.setState({
files: arr
})
}
发生的事情是文件对象被重新创建到数组中,然后我成功地给它一个新名称、一个 id 和一个预览值。
我尝试分配颜色值,但这失败了,因为颜色已经是对象中的一个值。
如何覆盖现有值?
解决方案
构造File
函数允许您在创建它时提供可选属性。尝试将所有属性放在那里,而不是稍后更改它们。
const newFile = new File([""], name, {
id: Math.random().toString(32),
color: arr[i].color,
preview: arr[i].preview
});
推荐阅读
- ios - Xamarin Forms 应用程序在后台提取期间崩溃
- javascript - $scope 没有更新
- botframework - MS Teams 日历深层链接:如何删除 Microsoft Teams 会议部分
- node.js - 如何在异步函数中返回axios的响应
- bash - systemd ExecStart 中的参数
- python - 使用 python/cartopy 设置 plt.colorbar 范围
- c# - Visual Studio 2019 - 通过数据网关连接到 SQL Server
- java - 无法自动接线。找不到“MyUserDetailsService”类型的 bean
- python - 从用户输入(表单)(pythong/flask)发送带有 gmail-api 的附件
- sql - 获取 x.66 和 x.99 之间的分数