将第一个字符大写字母添加到输入和数组(JavaScript)

时间:2018-10-19 12:31:20

标签: javascript arrays string function

我想做的是让用户输入自己的水果,并在那里放置一系列水果。我将对其进行整理,但是在此之前,我想将每个单词的第一个字符用大写字母表示,然后在html上的每个条目上用“ with”将其吐出。我不确定我是否走对了。任何帮助是极大的赞赏 !谢谢

let fruits = ["banana", "orange", "apple", "kiwi"];

function addFruits () {
let fruitInput = prompt ("Please Enter More Fruits").toLowerCase().split(" ");
let fruitsAdded = fruits.push(fruitInput);
let fruitsPushed = fruitsAdded.map(
    function(value){ 
        return value.replace(value.charAt(0), value.charAt(0).toUpperCase());
    });
fruits.sort();
document.getElementById("sortedFruits").innerHTML = fruits.join(" with ");

3 个答案:

答案 0 :(得分:1)

对我来说,有助于将事情分解一些。您想要输入并更新列表,然后想要格式化该列表以进行显示。我添加了一个列表和事件触发器,以使其易于演示。

// set up your list of fruit and the handles for your event/render
let fruits = ["banana", "orange", "apple", "kiwi"];
const wrapper = document.querySelector('#sortedFruits');
const button = document.querySelector('#add_button');

const render = () => {
  // build (and sort) a list from the fruits array
  const list = fruits
    .sort()
    // uppercase the first character and ensure the rest are lower
    .map(str => str.slice(0,1).toUpperCase() + str.slice(1).toLowerCase())
    // format item for render
    .map(fruit => `<li>${fruit}</li>`)
    .join('');
  
  // replace list with new list
  wrapper.innerHTML = list;
}

const addFruits = () => {
  // take user input
  const input = prompt('Please enter more fruit')
  // build array of fruit to add
  const newFruit = input
    .toLowerCase()
    .split(' ');
  
  // update fruit list
  fruits = [ ...fruits, ...newFruit ];
  // show updated list
  render();
}

// initial list
render();
// add event handler to trigger fruit addition
button.addEventListener('click', addFruits);
<section>
  <input type="button" name="add_fruit" value="Add More Fruit!" id="add_button" />
  <ul id="sortedFruits"></ul>
</section>

答案 1 :(得分:0)

我带了你的代码,它的工作原理是

  • 使用spread syntax ...推送数组的值,以将所有项目作为单个参数,
  • 删除Array#push的分配,因为它返回数组的新长度,而不是新数组或给定数组,
  • 将排序移到上方,因为这里需要排序数组
  • 现在从fruits中获取大写单词
  • Array#map的回调内部,将第一个字符作为大写字符串,并将字符串的resz与String#slice一起使用。

function addFruits() {
    let fruitInput = prompt("Please Enter More Fruits").toLowerCase().split(" ");
    fruits.push(...fruitInput);
    fruits.sort();
    let upperCased = fruits.map(function(value) {
        return value[0].toUpperCase() + value.slice(1);
    });
    document.getElementById("sortedFruits").innerHTML = upperCased.join(" with ");
}

let fruits = ["banana", "orange", "apple", "kiwi"];
addFruits();
<div id="sortedFruits"></div>

答案 2 :(得分:-1)

    function Firstupchar(letter) {
        return letter[0].toUpperCase() + letter.substring(1).toLowerCase()
    }

["one","two"].map(c => Firstupchar(c) ).join(" with ")