freecodecamp JavaScript学习(四)

Reverse a String
function reverseString(str) {
  //covert string to an array
   //var strArray=str.split('');
  //reverse the new array
   //strArray.reverse();
  //join the array to a string
  //return strArray.join('');
  return str.split('').reverse().join('');
}
Check for Palindromes
function palindrome(str) {
  // Good luck!
  var filteredStr;
  filteredStr=str.toLowerCase().split ('').filter(function(val){
    return (val>='a' && val<='z') || (val >='0' && val<='9');
  }).join('');

  if (filteredStr===filteredStr.split('').reverse().join('')){
    return true;
  }
  return false;
}
Find the Longest Word in a String
function findLongestWord(str) {
  //convert string to array
  var arr=str.split(' ');
  var arrLen=[];
  for(var i=0;i<arr.length;i++){
    arrLen.push({"name":arr[i],"strLen":arr[i].length});
  }
  arrLen.sort(function(a,b){
    return b.strLen-a.strLen;
  });
  return arrLen[0].strLen;
}
Title Case a Sentence
function titleCase(str) {
  var arr=str.split(' ');
  var newArr;

  newArr=arr.map(function(val,index){
    return val.substr(0,1).toUpperCase() + val.substr(1).toLowerCase();
  });
  return newArr.join(' ');
}

titleCase("I'm a little tea pot");
//I'm A Little Tea Pot
Return Largest Numbers in Arrays
function largestOfFour(arr) {
  // You can do this!
  var newArr=[];
  for(var i=0;i<arr.length;i++){
    arr[i].sort(function(a,b){
      return b-a;
    });
    newArr.push(arr[i][0]);
  }

  return newArr;
}

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);
//[9,35,97,1000000]
Repeat a string repeat a string
function repeatStringNumTimes(str, num) {
  // repeat after me
  var repeatStr;
  if(Number.isInteger(num) && num>0){
    repeatStr=str.repeat(num);
    return repeatStr;
  }
  return '';
}

repeatStringNumTimes("abc", 3);
//"abcabcabc"
Truncate a string

MDN上的slice

function truncateString(str, num) {
  // Clear out that junk in your trunk
  var newStr;
  if(str.length > num){
    if (num>3){
      newStr = str.slice(0,num-3) + '...';
      return newStr;
    }else{
      newStr = str.slice(0,num-str.length) + '...';
      return newStr;      
    }

  }
  return str;
}
truncateString("Absolutely Longer", 2);
//Ab...
truncateString("A-tisket a-tasket A green and yellow basket", 11)
var str1 = 'The morning is upon us.', // the length of str1 is 23.
    str2 = str1.slice(1, 8),
    str3 = str1.slice(4, -2),
    str4 = str1.slice(12),
    str5 = str1.slice(30);
console.log(str2); // OUTPUT: he morn
console.log(str3); // OUTPUT: morning is upon u
console.log(str4); // OUTPUT: is upon us.
console.log(str5); // OUTPUT: ""
var str = 'The morning is upon us.';
str.slice(-3);     // returns 'us.'
str.slice(-3, -1); // returns 'us'
str.slice(0, -1);  // returns 'The morning is upon us'

Chunky Monkey

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr=[];
  var tempArr=[];
  for(var i=0;i<arr.length;i++){
    tempArr.push(arr[i]);
    if(((i+1)%size===0) || ((i+1)===arr.length)){
      newArr.push(tempArr);
      tempArr=[];
    }
  }
  return newArr;
}

chunkArrayInGroups(["add11", "b", "c", "d", "dddee"], 3);
//[["add11","b","c"],["d",, "dddee"]]

Slasher Flick

MDN上的splice

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

MDN上的slice
-array.splice会改变原来的数组,删掉从start开始的deleteCount个数的元素,item1,item2会加在start这个位置

arr.slice()
arr.slice(begin)
arr.slice(begin, end)

-array.slice不改变原来的数组,会产生一个新的数组,删除begin到end-1的元素

Mutations

MDN上的string.indexOf
-查询字符串是否在当前字符串中存在。如存在,返回位置,不存在,返回-1

function mutation(arr) {
  if (arr.length>=2){
    var mapStr=arr[0];
    var checkStr=arr[1];
    for(var i=0;i<checkStr.length;i++){
      if(mapStr.toLowerCase().indexOf(checkStr.toLowerCase().substr(i,1)) === -1){
        return false;
      }    
    }
    return true;
  }
  return false;
}

mutation(["hello", "hey"]);
// should return false.
mutation(["hello", "Hello"]) 
//should return true

Falsy Bouncer

MDN上的Boolean
-Boolean(val),若参数为false, null, 0, “”, undefined, and NaN,则返回false
-任何对象作为输入参数,只要对象的值不为undefined or null,则返回true

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  var nwArr=arr.filter(function(val){
    var falsyOjb=Boolean(val);
    return falsyOjb;

  });
  return nwArr;
}

bouncer([7,NaN, "ate", "", false,undefined,0,-0, 9]);
//[7,"ate",9]

Seek and Destroy

1)命名参数只有一个不代表此函数只有一个参数,调用函数时不必和命名参数一致,arguments.length内属性可以获知有多少个参数传递给了函数
2)arguments是一个类似数组,不是一个真正的数组,只有一个属性length,使用Array.from将其转换为一个真正的数组
3)MDN上的arguments

function destroyer(arr) {

  var newArr=[];

//必须在arr.filter外面将arguments赋值给另外的变量,否则在arr.filter内使用的arguments将是filter内函数本身的参数(val)

  var args = Array.from(arguments);
 //检测第一个参数是否为数组
  if(Array.isArray(arr)){
    newArr=arr.filter(function(val){
      var flag=true;
       for(var i=1;i<args.length;i++){
         if(val==args[i]){
           flag=false;
           break;
         }
       } 
       return flag;
    });

    return newArr;
  }
  return "The first argument is not a array!";
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
//[1,1]

Caesars Cipher

-ROT13(回转13位)密码,
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm

[MDN:charCodeAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt)
-str.charCodeAt(index),得到string中参数位置的ascII码

[MDN:fromCharCode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode)
-String.fromCharCode(num1[, ...[, numN]]),num为ascii码,从ascii码得到字符

function rot13(str) { // LBH QVQ VG!

  var strArr=[];
 //iterate the str, and get every ascii code
  for(var i=0;i<str.length;i++){
    if(str.substr(i,1)>='A' && str.substr(i,1)<='M'){
      strArr.push(String.fromCharCode(str.charCodeAt(i)+13));
    }else if(str.substr(i,1)>='N' && str.substr(i,1)<='Z'){
      strArr.push(String.fromCharCode(str.charCodeAt(i)-13));
    }
    else{
      strArr.push(str.substr(i,1));
    }
  }

 //get the string from array  
  return strArr.join('');
}

// Change the inputs below to test
rot13("LBH QVQ VG");
//"YOU DID IT"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值