Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.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
Javascript 如何创建具有某些数组值的对象而不保存对数组的引用?_Javascript_Arrays_Typescript_Type Conversion_Aggregate - Fatal编程技术网

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
。这些都是财产名称,那么更像是什么?