简体   繁体   English

如何将键分配给JavaScript数组中的现有值

[英]How can I assign keys to existing values in a JavaScript array

I recovered an array with values from a previous method and I need to go through it and assign each of the values a key in alphabetical order. 我从以前的方法中恢复了一个带有值的数组,我需要遍历它,并按字母顺序为每个值分配一个键。

["T", "C", "α", "T(linked)", "C"]

This is my array, previously mentioned. 这是我前面提到的数组。 I want to know how, when crossing the array will I be able to assign it a key of alphabetical form, so that the final result was: 我想知道如何在穿越数组时为它分配一个字母形式的键,这样最终结果是:

["A:T", "B:C", "C:α", "D:T(linked), "E:C"]

Any advice will be welcome. 任何建议都将受到欢迎。 Thank you in advance. 先感谢您。

By having single elements, you could just map the values with a prefix. 通过使用单个元素,您可以仅将值与前缀映射。

 var data = ["T", "C", "α", "T(linked)", "C"], result = data.map((v, i) => `${(i + 10).toString(36).toUpperCase()}:${v}`); console.log(result); 

You can achieve it by using Array.prototype.map function. 您可以通过使用Array.prototype.map函数来实现。

 let a = ["T", "C", "α", "T(linked)", "C"]; a = a.map((val,index)=>{ return `${String.fromCharCode(65 + index )}:${val}`; } ) ; console.log(a); 

In your input array: 在您的输入数组中:

["T, C", "α", "T(linked), C"]

are "T, C" and "T(linked), C" supposed to be elements as is, or are you missing quotation marks? “ T,C”和“ T(链接),C”应该原样是元素,还是缺少引号? In other words, did you mean this? 换句话说,这是您的意思吗?

["T", "C", "α", "T(linked)", "C"]

You can use the map function. 您可以使用地图功能。 Using the code 使用代码

newArray = array.map((value, index) => ...)

will generate a new array with a function done for each value and index of the old array. 将生成一个新数组,并为旧数组的每个值和索引完成一个函数。

array = ["T", "C", "α", "T(linked)", "C"];
newArray = array.map((value, index) => `${String.fromCharCode(index + 65)}:${value}`);

newArray will be set to newArray将设置为

["A:T", "B:C", "C:α", "D:T(linked)", "E:C"]

If you don't understand that method of concatenating strings, use this instead. 如果您不了解这种连接字符串的方法,请改用此方法。

array = ["T", "C", "α", "T(linked)", "C"];
newArray = array.map((value, index) => String.fromCharCode(index + 65) + ":" + value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM