我想返回一个仅包含原始字符串数组值的第一个字母的数组。
例如:假设我有以下数组:
var array = ["gsss", "osgs", "ortr", "dges"];
并且我需要一些函数来返回这个:
["g", "o", "o", "d"]
答案 0 :(得分:5)
您可以使用map()
遍历数组。通过o[0]
var array = ["gsss", "osgs", "ortr", "dges"];
var result = array.map(o => o[0]);
console.log(result);
答案 1 :(得分:2)
您可以使用forEach
和charAt
来完成
var array = ["gsss", "osgs", "ortr", "dges"];
var result = new Array();
array.forEach(v =>{
result.push(v.charAt(0));
});
console.log(result);
答案 2 :(得分:1)
使用t = threading.Thread(target=c.run,args=(10,), daemon=True)
map()
答案 3 :(得分:1)
一种方法是:
// on the grounds that you may want to repeat the
// functionality but for a different index, we use
// compose a named function that takes two arguments.
// haystack: Array of strings from which you wish to
// retrieve the characters;
// index: (optional, defaults to 0), specifies the
// index from which you wish to retrieve the characters:
let charsAtNFrom = (haystack, index = 0) => {
// here we iterate over the Array using
// Array.prototype.map(), with an Arrow function:
return haystack.map(
// 'str' represents the current String of the Array
// of Strings over which we're iterating; and we return
// the character at the specified index:
(str) => str.charAt(index)
);
},
stringArray = ["gsss", "osgs", "ortr", "dges"],
firstLetters = charsAtNFrom(stringArray);
console.log(firstLetters);
参考文献:
答案 4 :(得分:0)
使用Array Reduce返回一个新数组:
let arr = ["gsss", "osgs", "ortr", "dges"];
let newArray = arr.reduce((newArr, curVal)=>{
return newArr.push(curVal.charAt(0));
}, []);
答案 5 :(得分:0)
String[] array = new String[]{"gsss", "osgs", "ortr", "dges"};
char array1[] = new char[array.length]; //creating another Character Array
for(int i = 0;i<array.length;i++) { //taking first character for each element of the Array
array1[i]= array[i].charAt(0);
}