javascript - 使用过滤器和映射方法将数组中某些元素的首字母大写 - JavaScript

标签 javascript arrays dictionary filter

我正在尝试将数组中某些元素的首字母大写。我需要跳过以字母 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/

相关文章:

C++ STL 映射,其键为 shared_ptr<struct tm>

javascript - 动态网站JS框架

javascript调试问题

javascript - 为什么我的冒泡排序函数会跳过 else if 并返回 undefined?

java - 使用循环 for 将内容添加到 linkedList java

java - 从列表中删除、添加和使用项目

javascript - 在 RxJS 中,如何在没有主题的情况下直接链接 pub 子系统中的生产者和消费者?

arrays - 从字符串数组创建数组对象

function - 获取不同内容 map 的所有 map 键[字符串]

python - 将列表值转换为字典作为键和值