我有一个数组,我想把它改成大写,但我无法成功。请帮帮我。
var array2 = ["melon","banana","apple","orange","lemon"];
array2.toUpperCase()
我也尝试了下面的方法,但它也不起作用。
array2.map(toUpperCase);
提前致谢!
我有一个数组,我想把它改成大写,但我无法成功。请帮帮我。
var array2 = ["melon","banana","apple","orange","lemon"];
array2.toUpperCase()
我也尝试了下面的方法,但它也不起作用。
array2.map(toUpperCase);
提前致谢!
你应该在 map 函数中使用处理函数:
var array2 = ["melon","banana","apple","orange","lemon"];
array2 = array2.map(function(x){ return x.toUpperCase(); })
编辑:是的,您可以这样做。
toUpper = function(x){
return x.toUpperCase();
};
array2 = array2.map(toUpper);
.map
不关心它来自哪里。 - Felix KlingtoUpperCase()
不会改变值。
尝试:
array2 = array2.map(function (e) {
return e.toUpperCase()
});
你可以使用这个:
var a = ['this','is','test'];
a.map(f=>{ return f.toUpperCase(); });
return
+ 大括号是不必要的... - General Grievance我建议使用Map,但这有一种替代方法,可能有助于理解在对象原型上使用apply的人。
这是一个示例,展示了一个数组如何使用apply借用String对象的.toUpperCase()方法,并将其应用于该数组。使用.apply()方法将数组强制转换为字符串,然后使用.split()方法将其再次转换为大写的数组。
arr = ["fulu", "nulu", "hulu"];
var arrToUp = String.prototype.toUpperCase.apply(arr).split(",");
console.log(arrToUp)
//["FULU", "NULU", "HULU"]
arr = ["fu,lu", "nulu", "hulu"]
。 - Jose Ricardo Bustos M.for(var i = 0; i < array2.length; i++){
array2[i] = array2[i].toUpperCase();
}
Array.prototype.toUpperCase = function(){
return this.map( (el) => (typeof el === "string") ? el.toUpperCase() : el)}
const yourArray = ["apple","banana"];
const upperCasedArray = String(yourArray).toUpperCase().split(",");
//OR
const upperCasedArray = yourArray.toString().toUpperCase().split(",");
发生的是,首先我们将数组转换为字符串,然后使用字符串的 toUpperCase() 方法使该字符串全为大写,然后使用“,”拆分它,这样我们就得到了一个新的大写数组。
你正在尝试更改数组的值。为此,您必须先迭代数组,然后在数组上应用所需的方法。这样,每个值都将采用应用的方法。
const array2 = ["melon","banana","apple","orange","lemon"];
/*create another variable (newArr) which would store your "loop through array2"*/
const newArr = array2.map(arr => arr.toUpperCase());
console.log(newArr);
证毕
回顾一下:
有两种主要的方法可以做到这一点:
1. 使用现代的Javascript ES6版本,带有箭头函数和map()迭代器:
// the test array
const items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'];
// declare the function with arrow function using the map iterator and the
// toUpperCase() buildin method
const countItems = arr => arr.map(item => item.toUpperCase());
2. 使用旧的好函数风格,结合简单的for循环、toUpperCase()内置方法和push()方法
// the test array
const items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'];
// the old way
function countItems(arr) {
newarray = [];
for (let i = 0; i < arr.length; i++) {
newarray.push(arr[i].toUpperCase());
}
return newarray;
};
3. 使用上述任何代码片段调用该函数
console.log(countItems(items));
// 应该打印
[ 'ITEM1', 'ITEM2', 'ITEM3', 'ITEM4', 'ITEM5', 'ITEM6' ]
希望这个答案能为您想要构建的任何东西增添一块小石头
var array2 = ["melon","banana","apple","orange","lemon"];
array2.map(fruit => fruit.toUpperCase())
toUpperCase
方法,b) 没有toUpperCase
函数。 - Felix Kling