简体   繁体   English

如何在javascript中设置数组对象的键值?

[英]how to set a value of a key of an array object in javascript?

I'm creating a drag and drop files(multiple files can be selected) feature.我正在创建拖放文件(可以选择多个文件)功能。 WHere user can select multiple files.I want to convert the size of file from byte to mb.用户可以在这里选择多个文件。我想将文件的大小从字节转换为 mb。 . . the function to get all the files获取所有文件的函数

scripts.js脚本.js

const handleFiles = (files) => {
  files = [...files];

//converting bytes into mb and trying to assign it back to size key
  files.forEach(function (file) {                      <----these lines need to be changed
    file["size"] = `${(file["size"] / 1024 ** 2).toFixed(2)} mb`; <------
  });                                                  <-----
  console.log(files);
};

I'm getting this as an output of files variable value in console.我将此作为控制台中文件变量值的输出。 这是我在文件中得到的(对象列表)

Why i'm using spread operator?为什么我使用传播运算符?

Ans: If i don't use the spread operator and user select only one file then it is passed as an object and not as a list of object Ans:如果我不使用扩展运算符并且用户只选择一个文件,那么它会作为一个对象而不是一个对象列表传递

How can i set the value of each size key of an object with new value.如何使用新值设置对象的每个大小键的值。

File.size is a read-only property, you cannot change it (see here: https://developer.mozilla.org/en-US/docs/Web/API/File#instance_properties ). File.size 是只读属性,您无法更改它(请参阅此处: https : //developer.mozilla.org/en-US/docs/Web/API/File#instance_properties )。 If you want to show file size in Mb in your UI, you will have to get the File.size (or File["size"], like you are doing), and process it like you do in your function to show it in the UI (have the function return an array of sizes, or include the size formatting in the rendering part of your app), but you cannot change the property on the File instances themselves.如果要在 UI 中以 Mb 为单位显示文件大小,则必须获取 File.size(或 File["size"],就像您在做的那样),并像在函数中一样处理它以将其显示在UI(让函数返回大小数组,或在应用程序的呈现部分包含大小格式),但您不能更改 File 实例本身的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM