JavaScript算法练习:确认末尾字符算法

2018-03-0906:08:02WEB前端开发Comments2,111 views字数 571阅读模式

确认末尾字符算法
检查一个字符串(str)是否以指定的字符串(target)结尾。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html

如果是,返回true;如果不是,返回false。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html

这道题比较简单,但一开始的时候我把target想成是一个字符了,没有好好读题。还是写好在执行的过程中发现执行总是不通过。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html

思路:分割成数组,利用JS方法取到和target字符相同长度的字符,再和target做比较。(后来发现并不需要分割数组,因为target本身就是个字符串。。。)
Answer:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html

function confirmEnding(str,target){
    var arr = str.substr((str.length - target.length),str.length-1);
    if(arr == target){
        return true;
    }else{
        return false;
    }
}
confirmEnding("He has to give me a new name", "name");

substr()方法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html

8、重复操作算法
循环拼接一个指定的字符串 num次,如果num是一个负数,则返回一个空字符串。
Answer:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html

function repeat(str,num){
    var a = '';
    if(str < 0){
        str = a;
    }else{
        for(var i = 0;i < num;i++){
            a += str;
        }
    }
    return a;
}
repeat("abc", 3);
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/1350.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/1350.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定