【问题标题】:How to take values from 2 Array and make it into 1 value in a new array?如何从 2 数组中获取值并将其转换为新数组中的 1 值?
【发布时间】:2021-03-03 11:35:00
【问题描述】:

我有 2 个数组: "interfaceTitles" 的值为 "USB 端口"、"数字输入"、"RS232, ... “interfaceAmounts”,值为“3”、“20”、“1”、...

我需要一个具有组合值的合并数组。所以新数组应该有以下值: “3 个 USB 端口”、“20 个数字输入” ...

所以它不仅仅是连接,它的融合:D

interfacesAdded = interfaceAmounts && interfaceTitles 不起作用

interfacesAdded = interfaceAmounts + interfaceTitles 把它变成一个字符串

“interfacesAdded”声明为const interfacesAdded: any = ...

我该怎么办,搜索功能对我没有帮助,抱歉我有点缺乏经验:(

问候

【问题讨论】:

    标签: arrays merge


    【解决方案1】:

    下面使用map函数循环interfaceTitles列表,并返回一个新列表,其中元素是两个列表中的对应元素,由空格连接。

    const result = interfaceTitles.map((_, i) => {
        return interfaceAmounts[i] + " " + interfaceTitles[i];
    });
    

    希望这就是你要找的。​​p>

    【讨论】:

      【解决方案2】:

      我认为您可以添加您正在使用的语言来帮助更好地回答, 不同语言的逻辑是一样的,我是用js做的。 承认要连接的字符串在2个数组的相同位置:

      const array1 = [1, 4, 9, 16];
      const array2 = ['a','b','c','d'];
      // pass a function to map
      // care in js we can use the + to concat string
      // map will iterate over each element of array1
      // x will be the current element of array1
      // index will be the index of the current element,
      // used to get the corresponding element in array2
      const map1 = array1.map((x,index) => x+array2[index]);
      
      console.log(map1);
      // expected output: > Array ["1a", "4b", "9c", "16d"]
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多