typescript 使用键值将项目推送到打字稿中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42441181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pushing items to an array in typescrip with key value
提问by Geoff
I would like to push an array to another array but the result generates an incorrect result
我想将一个数组推送到另一个数组,但结果生成了不正确的结果
let pusheditems:any[] = [];
pusheditems.push(this.yesvalue);
pusheditems.push(this.selectedtruck);
Later when i console.log(pusheditems)
后来当我 console.log(pusheditems)
Am getting an array of type
我得到一个类型的数组
array(0->yes array, 1->select truck array)
What am looking for is to change the index values of 0,1 to strings like yes, truck
我正在寻找的是将 0,1 的索引值更改为像 yes, truck 这样的字符串
So i would expect to get
所以我希望得到
array(yes->yes array, truck->select truck array)
I have also tried
我也试过
pusheditems.push({yes:this.yesvalue}); //adding yes
pusheditems.push({truck:this.selectedtruck}); //adding truck
But this doesnt work
但这不起作用
The values of
的价值
this.yesvalues and this.selectedtruck are also arrays
What do i need to add further
我需要进一步补充什么
回答by Igor Jankovi?
Thing you are trying to achieve is to create object, not an array.
您试图实现的是创建对象,而不是数组。
You can do it:
你能行的:
let pusheditems = {};
pusheditems[this.yesvalue] = this.selectedtruck;
回答by Petr Adam
In Typescript, arrays can have keys only of type number. You need to use Dictionary
object, like:
在 Typescript 中,数组只能有类型为 number 的键。您需要使用Dictionary
对象,例如:
let pusheditems: { [id: string]: any; } = {}; // dictionary with key of string, and values of type any
pusheditems[this.yesvalue] = this.selectedtruck; // add item to dictionary