FCC JS基础算法题(9):Truncate a string(截断字符串)

  先看一下题目描述:

  如果字符串的长度比指定的参数num长,则把多余的部分用...来表示。切记,插入到字符串尾部的三个点号也会计入字符串的长度。但是,如果指定的参数num小于或等于3,则添加的三个点号不会计入字符串的长度。

  简单的if嵌套就可以解决,最开始我是这么做的:

  

function truncate(str, num) {
  // 请把你的代码写在这里
  var newStr = "";
  if(str.length > num){
    if(num <= 3){
      newStr = str.slice(0,num) + "...";
    }else{
      newStr = str.slice(0,num-3) + "...";
    }
  }else{
    newStr = str;
  }
  return newStr;
}

truncate("A-tisket a-tasket A green and yellow basket", 11);

  写完可以达到效果,但是中间有些步骤可以去掉,比如这个变量。看了网上的方法之后,写出最终效果:

  

function truncate(str, num) {
  // 请把你的代码写在这里
  if(num<str.length){
    if(num>=3){
       str= str.slice(0,num-3)+"...";
    }else{
      str= str.slice(0,num)+"...";
    }
  }
  return str;
}

truncate("A-tisket a-tasket A green and yellow basket", 11);

猜你喜欢

转载自www.cnblogs.com/humengxiangfeng/p/10503816.html