我正在尝试将数组中某些元素的首字母大写。我需要跳过以字母 c 开头的元素。我还需要使用过滤器和映射方法。我查看了MDN的文档,一头雾水。这是为了学校,所以我真的需要理解代码为何有效;我不只是在寻找答案。这是我的 html:
<div><strong>Sorted Fruit:</strong> <span id="sorted-fruit"></span></div>
<div><strong>Capitalized Fruit without Cs:</strong> <span id="capitalized-fruit"></span></div>
这是我的 JS:
// (1) Iterate through each fruit type and write it to the console
// using a for loop.
// (2) Use Array's methods "sort" and "join" to print an alphabetically
// sorted comma delimited list of fruit in the span with id "sorted-fruit"
// (3) Use ECMAScript 5 Array methods "filter" and "map" and Array method
// "join" to print out a comma delimited list of fruit that are
// capitalized (just the first letters); skip those that contain the
// letter "c" in them.
(function() {
var fruit = [
"apple",
"orange",
"peach",
"cherry",
"pear",
"apricot",
"banana",
"guava",
"melon"
];
fruit.sort();
var myFruit = fruit.join(', ');
for (i = 0; i < fruit.length; i++) {
console.log(myFruit);
}
document.getElementById('sorted-fruit').innerHTML = myFruit;
// Your code goes here ...
}());
最佳答案
如果您想缩短代码中需要编写的内容,箭头函数非常棒!
// To capitalize the first letter of remaining words, using 'w' as the variable for each word
const fruit = fruit.map(w => w.charAt(0).toUpperCase() + w.slice(1));
var fruit = [
"apple",
"orange",
"peach",
"cherry",
"pear",
"apricot",
"banana",
"guava",
"melon"
]
const fruitChanged = fruit.map(w => w.charAt(0).toUpperCase() + w.slice(1));
console.log(fruitChanged)
如果您要迭代数组,那么映射数组方法也很棒。 MDN - 数组方法:Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
关于javascript - 使用过滤器和映射方法将数组中某些元素的首字母大写 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448504/