尝试在字符串末尾添加句号

时间:2020-06-24 03:08:01

标签: javascript

我目前正在学习JS,并且正在阅读MDN网络文档。我正在尝试完成此exercise 4,要求我添加句号。

运行代码时,出现以下错误:TypeError:无法读取未定义的属性'charAt'

if (fixedQuote.str.charAt(fixedQuote.str.length-1) != ".") {
            fixedQuote.str = fixedQuote.str + "."
        }

这是整个练习。有人可以解释我在做什么错吗?

let quote = 'I dO nOT lIke gREen eGgS anD HAM';
    
    // Add your code here
    let fixedQuote = quote[0].toUpperCase() + quote.substring(1);

    fixedQuote = fixedQuote.replace("green eggs and ham", "onions");

    if (fixedQuote.str.charAt(fixedQuote.str.length-1) != ".") {
        fixedQuote.str = fixedQuote.str + "."
    }
     
    // Don't edit the code below here!
    
    section.innerHTML = ' ';
    let para1 = document.createElement('p');
    para1.textContent = fixedQuote;
    let para2 = document.createElement('p');
    para2.textContent = finalQuote;
    
    section.appendChild(para1);
    section.appendChild(para2);
    

3 个答案:

答案 0 :(得分:1)

只需使用fixedQuote,它是一个字符串,而不是fixedQuote.str,它是未定义的。另请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

let quote = 'I dO nOT lIke gREen eGgS anD HAM';
    
    // Add your code here
    let fixedQuote = quote[0].toUpperCase() + quote.substring(1);

    fixedQuote = fixedQuote.replace("green eggs and ham", "onions");

    if (fixedQuote.charAt(fixedQuote.length-1) != ".") {
        fixedQuote = fixedQuote + "."
    }
     
    // Don't edit the code below here!
    section = document.querySelector("section");
    section.innerHTML = ' ';
    let para1 = document.createElement('p');
    para1.textContent = fixedQuote;
    let para2 = document.createElement('p');
    //para2.textContent = finalQuote;
    
    section.appendChild(para1);
    section.appendChild(para2);
    
<section></section>

答案 1 :(得分:0)

    let fixedQuote = quote[0].toUpperCase() + quote.substring(1);
    fixedQuote = fixedQuote.replace("green eggs and ham", "onions");

    if (fixedQuote.charAt(fixedQuote.length-1) != ".") {
        fixedQuote= fixedQuote + "."
    }

答案 2 :(得分:0)

不使用str尝试此操作。在charAt()之前,它可以正常工作

let quote = 'I dO nOT lIke gREen eGgS anD HAM';
    
    // Add your code here
    let fixedQuote = quote[0].toUpperCase() + quote.substring(1);

    fixedQuote = fixedQuote.replace("green eggs and ham", "onions");

    if (fixedQuote.charAt(fixedQuote.length - 1) != ".") {
        fixedQuote = fixedQuote + "."
    }

    console.log(fixedQuote);

相关问题