JavaScript:如何返回字符串中每个单词的首字母

时间:2019-03-17 02:07:15

标签: javascript

我有这个常量:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

,我正在尝试返回每个单词的第一个字母。 我所拥有的:

const firstLetter = animals.map(animal => {
return_

6 个答案:

答案 0 :(得分:3)

在函数origin/master的处理程序中,对字符串进行解构以获取第一个字母,并将其用作每个索引的结果。

map
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const result = animals.map(([letter]) => letter);
console.log(result);

答案 1 :(得分:1)

是否要返回数组的每个单词的首字母(问题说“ string”)。

您快到了! 您可以这样做:

animals.map(a => a[0]);

答案 2 :(得分:0)

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

const firstLetter = [];
for(var i = 0; i < animals.length; i++) {
  firstLetter.push(animals[i][0]);
}
console.log(firstLetter);

如果animals[i][0]不起作用,则可以始终使用animals[i].charAt(0)。我的解决方案是一个更基本的解决方案,但它更好,因为它不使用内置函数。

答案 3 :(得分:0)

.map() animals数组。在每个单词.split('')上将其转换为字母,然后.shift()以获得第一个字母。


const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let greeting = animals.map(animal => animal.split('').shift());

console.log(JSON.stringify(greeting));

答案 4 :(得分:0)

使用#Artificial data set Consumption <- c(501, 502, 503, 504, 26, 27, 55, 56, 68, 69, 72, 93) Gender <- gl(n = 2, k = 6, length = 2*6, labels = c("Male", "Female"), ordered = FALSE) Income <- c(5010, 5020, 5030, 5040, 260, 270, 550, 560, 680, 690, 720, 930) df3 <- data.frame(Consumption, Gender, Income) df3 # GLM Regression fm1 <- glm(Consumption~Gender+Income, data=df3, family=poisson) summary(fm1) # ANOVA anova(fm1,test="Chi") #Genders are different than I ajusted one model for male and another for Female #Male model df4<-df3[df3$Gender=="Male",] fm2 <- glm(Consumption~Income, data=df4, family=poisson) summary(fm2) #Female model df5<-df3[df3$Gender=="Female",] fm3 <- glm(Consumption~Income, data=df5, family=poisson) summary(fm3) #Create preditions amd confidence interval Predictions <- c(predict(fm2, type="link", se.fit = TRUE), predict(fm3, type="link", se.fit = TRUE)) df3_combined <- cbind(df3, Predictions) df3_combined$UCL<-df3_combined$fit + 1.96*df3_combined$se.fit df3_combined$LCL<-df3_combined$fit - 1.96*df3_combined$se.fit df3_combined<-df3_combined[,-(5:9)] df3_combined<-as.data.frame(df3_combined) #Plot library(tidyverse) library(ggplot2) df3_combined %>% gather(type, value, Consumption) %>% ggplot(mapping=aes(x=Income, y=value, color = Gender, lty = type)) + geom_point() + geom_line(mapping=aes(x=Income, y=exp(fit))) + geom_smooth(mapping=aes(ymin = exp(LCL), ymax = exp(UCL)), stat="identity") # 获取每个单词的首字母,然后使用map将它们组合成字符串:

join

答案 5 :(得分:0)

编写“ firstLetter”功能,代码将为:

const firstLetter = (word) => word[0]
const result = animals.map(firstLetter);