使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript

Use filter and map methods to capitalize the first letter of certain elements within an array - JavaScript

本文关键字:第一个 元素 -JavaScript map filter 方法 数组 使用      更新时间:2023-09-26

我正在尝试实现数组中某些元素的第一个字母的大写。我需要跳过以字母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);
});

但我想让你拆开这个解决方案,弄清楚它在做什么。