如何将数组内容转换为大写?

时间:2017-08-18 12:41:21

标签: javascript

是否有一种非向后的方法可以将一个数组索引转换为大写字符串? 我不想拆分,循环或其他任何东西,因为我只需要这一个字符串。

colors = [ "red", "green", "blue" ];
red = colors[0];
redUpper = red.toUppercase();

这不起作用,因为toUppercase()是一个字符串函数。我知道。我只是在寻找实现这一目标的最简单方法。

4 个答案:

答案 0 :(得分:9)

如果您只想要第一个元素大写,可以使用String#toUpperCase函数:

const colors = [ "red", "green", "blue" ];
const redUpper = colors[0].toUpperCase();
console.log(redUpper);

如果您想要全部,请使用Array#Map

const colors = [ "red", "green", "blue" ];
console.log(colors.map(a => a.toUpperCase()));

答案 1 :(得分:3)

您可以使用

执行此操作

const colors = [ "red", "green", "blue" ];
console.log(colors.map(function(x){
    return x.toUpperCase();
}));

如果要将第一个元素更改为大写,请使用

const colors = [ "red", "green", "blue" ];
colors[0] = colors[0].toUpperCase();
console.log(colors);

答案 2 :(得分:2)

您需要将值分配给要更改的数组元素

var arr = [ "red", "green", "blue" ];
arr[0] = arr[0].toUpperCase()
console.log(arr)

答案 3 :(得分:1)



colors = [ "red", "green", "blue" ];
console.log(colors[0].toUpperCase())




您的代码中出现拼写错误:toUppercase != toUpperCase