Javascript 如何创建具有某些数组值的对象而不保存对数组的引用?
换言之;我怎样才能转换Javascript 如何创建具有某些数组值的对象而不保存对数组的引用?,javascript,arrays,typescript,type-conversion,aggregate,Javascript,Arrays,Typescript,Type Conversion,Aggregate,换言之;我怎样才能转换 // an array of length >= 3 let myArray = returnOfSomeParametricFunction(); // assuming repeating rhs removes dryness let myObj = { staticKeyName: myArray[1], anotherStaticKeyName: myArray[2] }; 一艘班轮。也许是这样的: let myObj = returnOfSomePa
// an array of length >= 3
let myArray = returnOfSomeParametricFunction(); // assuming repeating rhs removes dryness
let myObj = { staticKeyName: myArray[1], anotherStaticKeyName: myArray[2] };
一艘班轮。也许是这样的:
let myObj = returnOfSomeParametricFunction().reduce(arr=> { staticKeyName: arr[1], anotherStaticKeyName: arr[2] };
在这种情况下,如果我需要在一行中完成,并且不在与
myObj
相同的范围内引入新变量,并且我不关心可读性,我会使用如下箭头函数:
let myObj = (a => ({ staticKeyName: a[1], anotherStaticKeyName: a[2] }))(
returnOfSomeParametricFunction());
您可以验证myObj
是否具有正确类型的属性。例如,给定
declare function returnOfSomeParametricFunction(): [Date, number, string];
然后myObj
将具有以下类型:
/*
let myObj: {
staticKeyName: number;
anotherStaticKeyName: string;
}
*/
好吧,希望这会有帮助;祝你好运
注意数组索引从0开始,而不是1。人们确实需要克服“单线性”的问题…比如
(a=>({staticKeyName:a[1],另一个staticKeyName:a[2]}))(returnOfSomeParametricFunction())
?@hereticsmonkey,但他们并没有尝试将变量命名为staticKeyName
和另一个staticKeyName
。这些都是财产名称,那么更像是什么?