【问题标题】:Pushing items to an array in typescript with key value使用键值将项目推送到打字稿中的数组
【发布时间】:2017-07-15 10:27:11
【问题描述】:

我想将一个数组推送到另一个数组,但结果生成的结果不正确

let pusheditems:any[]  = [];
pusheditems.push(this.yesvalue);
pusheditems.push(this.selectedtruck);

后来我console.log(pusheditems)

我得到一个类型的数组

array(0->yes array, 1->select truck array)

我正在寻找的是将 0,1 的索引值更改为像 yes, truck 这样的字符串

所以我希望得到

array(yes->yes array, truck->select truck array)

我也试过

pusheditems.push({yes:this.yesvalue});  //adding yes
pusheditems.push({truck:this.selectedtruck}); //adding truck

但这不起作用

价值观

this.yesvalues and this.selectedtruck are also arrays

我还需要补充什么

【问题讨论】:

    标签: arrays angular typescript


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:

      您想要实现的是创建对象,而不是数组。

      你可以做到的:

      let pusheditems = {};
      pusheditems[this.yesvalue] = this.selectedtruck;
      

      【讨论】:

        猜你喜欢
        • 2017-12-18
        • 2022-10-12
        • 1970-01-01
        • 2020-04-01
        • 2017-10-07
        • 2020-06-04
        • 2021-05-07
        • 1970-01-01
        • 2017-03-06
        相关资源
        最近更新 更多