使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript
Use filter and map methods to capitalize the first letter of certain elements within an array - JavaScript
我正在尝试实现数组中某些元素的第一个字母的大写。我需要跳过以字母c开头的元素。我还需要使用filter和map方法。我在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)
此外,如果要遍历数组,map数组方法也很好。MDN-数组方法:映射https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
您的第3部分解决方案:
// Filter out entries with the letter 'c'
fruit = fruit.filter(function (el) {
return el.indexOf('c') === -1;
});
// Capitalize the first letter of all remaining strings
fruit = fruit.map(function(string){
return string.charAt(0).toUpperCase() + string.slice(1);
});
但我想让你拆开这个解决方案,弄清楚它在做什么。
相关文章:
- 使用数据上的角度更改设置集合的第一个元素的动画
- 在javascript数组中推送多个值并获取第一个元素
- Angular js将只显示ng repeat中的第一个元素
- 使用+=运算符未定义对象中的第一个元素
- javascript window.addEventListener,覆盖了第一个元素的配置
- 如何访问 JSON 对象数组的第一个元素
- 第一个元素和最后一个元素之间的连续循环
- 要插入二叉树的第一个元素,请将其放在左边还是右边
- 向下滚动时覆盖页面的第一个元素或块
- 数组未发送所有元素,只获取第一个元素
- 创建每个数组的第一个元素的数组
- 只显示ng重复的第一个元素
- CKEditor:以小部件作为第一个元素,选择所有在Chrome中不工作的
- 从Web视图上显示的页面部分获取第一个元素
- 有没有更好的方法来访问用JQuery选择器选择的第一个元素
- JQuery验证仅适用于提交的表单中的第一个元素.[打算验证所有内容]
- jQuery导航菜单没有't更新第一个元素
- jQuery如何删除第一个元素前的逗号
- 如何获取数组第一个元素的范围
- 使用 Dart 时,我正在创建一个点击事件的 DOM 类.它只拾取第一个元素,我如何让它在所有元素上发射