销毁array.map()中的对象属性并将对象保留为参数 [英] Destruct object properties in array.map() and keep object as parameter
问题描述
是否可以破坏对象的属性,同时将对象保留为array.map()
函数中的参数?
Is it possible to destruct the properties of an object while keeping the object as a parameter inside an array.map()
function?
基于此问题我尝试了以下操作,但失败了(解析错误)
Based on this question I tried the following but failed (parsing error)
this.state.files.map(((file, {param1, param2} = file), i) => (
<div key={i}>
<p>{param1}</p>
<button onClick={this.editFile(file)} />
</div>
)
推荐答案
One way to achieve this would be to use the default parameters syntax, like so:
const test = (input, { a, b } = input) => [ a, b ]
console.log(test({ a: 1, b: 2 })) // [ 1, 2 ]
没有第二个参数传递给上面的函数,因此第二个参数默认为第一个参数,然后将其销毁.
No second parameter is passed to the function above, so the second parameter defaults to the first parameter, then it is destructed.
该参数只能在声明后使用,因此将无法使用:
The parameter can only be used after it has been declared, so this won't work:
const test = ({ a, b } = input, input) => [ a, b ]
console.log(test(undefined, { a: 1, b: 2 }))
// Uncaught ReferenceError: input is not defined at test
这也仅在没有传递参数的情况下有效,因此,在将回调传递给Array#map
的情况下,必须声明所有传递的参数,以便可以声明默认参数.
This can also only work if no parameter is passed, so in the case of a callback being passed to Array#map
, you must declare all of the parameters being passed so that you can declare the default parameter.
以您的示例为例:
this.state.files.map((file, i, files, { param1, param2 } = file) => (
<div key={i}>
<p>{param1}</p>
<button onClick={this.editFile(file)} />
</div>
))
这篇关于销毁array.map()中的对象属性并将对象保留为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!