Some algorithms of basic problems JS. Reprinted from other blog.

1, flip the string

Copy the code
 
Examples (required: first converted into a string array, then the aid of method Reverse array inverted order of the array, and finally the array into a string) 

function ReverseString (STR) { 
  STR = str.split ( '') Reverse ().. the Join ( ''); 
  return STR; 
} 
ReverseString ( "Hello"); 
// Split method to convert the string into an array
// Reverse method of reversing the order of the array
// join method to the array into a string
 
Copy the code

 

2, a calculated integer factorial

Copy the code
Examples (if using an n to represent an integer factorial represents the product of all less than or equal to n an integer factorial commonly abbreviated as n; for example:.!! 5 = 1 * 2 * 3 * 4 * 5 = 120) 
requires:  should return 1. function factorialize (NUM) { IF (NUM <. 1) { return. 1; } the else { return factorialize NUM * (. 1-NUM); } } factorialize (. 5);factorialize(0)
 
Copy the code

 

3, if the given string is a palindrome, returns true, otherwise, returns false.

Copy the code
 
If a string ignore punctuation, capitalization and spaces, is the opposite of the read and read exactly the same, then the string is palindrome (palindromes). 
Note that string need to remove extra spaces and punctuation, and then converted to lower case string to verify that the string is a palindrome. 

Palindrome function (STR) { 
  aStr str.replace = (/ [0-9A-Za-Z ^] / G, '') the toLowerCase ();. 
  .. astr.split BSTR = ( "") Reverse () the Join ( ""); 
  IF (aStr === BSTR) { 
    return to true; 
  } the else { 
    return to false; 
  } 
} 
Palindrome ( "Eye"); 

// also be a regular expression:
aStr str.replace = (/ [\ | ! \ ~ | \ `| \ | \ @ | \ # | \ $ | \% | \ ^ | \ & | \ * | \ (| \) | \ - | \ _ | \ + | \ = | \ | | \\ | \ [| \] | \ {| \} | \; | \: | \ "|? \ '| \, | \ <|. \ | \> | \ / | \] / g," ") .toLowerCase ();
 
Copy the code

 

4, to find the longest sentence word provided, and calculates its length.

Note: The function's return value should be a number.

Copy the code
 
findLongestWord function (STR) { 
// converted into an array 
  var aStr str.split = ( ""); 
// string length of each array element is compared, in accordance with the length of the string array are arranged from large to small order. 
  astr.sort BSTR = var (function (A, B) { 
    return-to b.length a.length; 
  }); 
// remove the first array element (i.e. the maximum length of the string) 
  var lenMax BSTR = [0 ] .length; 
// returns the length value 
  return lenMax; 
} 

findLongestWord ( "Quick of The Brown Fox jumped over the lazy The Dog"); 

// result: 6
 
Copy the code

 

5, to ensure that the first letter of each word in a string capitalized, the rest lowercase.

Copy the code
 
function titleCase(str) {
  var astr=str.toLowerCase().split(" ");
  for(var i=0 ; i<astr.length; i++){
    astr[i]=astr[i][0].toUpperCase()+astr[i].substring(1,astr[i].length);
  }
  var string=astr.join(" ");
  return string;
}
titleCase("I'm a little tea pot");

//结果:I'm A Little Tea Pot
 
Copy the code

 

6, the right large array contains four small array, respectively, each of the small maximum is found in the array, and then put them together, forming a new array.

Copy the code
 
function largestOfFour(arr) {
  var newArr=[];
  for(i=0;i<arr.length;i++){
    arr[i].sort(function(a,b){
      return b-a;
    });
    
    newArr.push(arr[i][0]);
  }
    return newArr;

}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
 
Copy the code

 

7, a check string ( str) if (a specified character string target) at the end.

   If so, it returns true; if not, it returns false.

Copy the code
 
confirmEnding function (STR, target) { 
  var len = target.length; 
  var = aStr str.substr (-len); 
  IF (aStr === target) { 
    return to true; 
  } the else { 
    return to false; 
  } 
} 
confirmEnding ( "Bastian "," n-"); 

// syntax: substr () method returns a substring of a string of specified length from a specified position to start
  str.slice(beginSlice[,endSlice]);
 
Copy the code

 

8, a repeated string specified  numtimes, if numa negative return an empty string.

Copy the code
 
REPEAT function (str, NUM) { 
  var str = aStr; 
  // str initial value is assigned to the aStr 
  IF (NUM <0) { 
    return ""; 
  } the else { 
    for (var I = 0; I <-NUM. 1; ++ I) { 
    // index starts from 0, the index cycle num-1 times; 
      str + = aStr; 
    // every cycle, plus an initial value str 
    } 
    return str; 
  } 
} 

REPEAT ( "ABC",. 3); 

// The results: abcabcabc
 
Copy the code

 

9, cut off a string!

    If the length of the string parameters than the specified numlength, put the unnecessary parts ...are represented.

    Remember, inserted into the end of the string number three points will be included in the length of the string.

    However, if the specified parameter numis less than or equal to 3, the addition of three dots included in the length of the string will not.

Copy the code
 
function truncate(str, num) {
  var len=str.length;
  var astr=str.slice(0,num-3);
  var bstr=str.slice(0,num);
  if(len>num){
    if(num<=3){
      return bstr+'...';
    }else{
      return astr+'...';
    }
  }else{
    return str;
  }
}

truncate("A-tisket a-tasket A green and yellow basket", 11);
//结果:A-tisket...
// use the syntax: slice()extract part of a string and returns the new string;
  str.slice(beginSlice[,endSlice]);
 
Copy the code
 

10, for an array arrin accordance with the specified size of the array sizeis divided into several array blocks.

For example: the chunk ([1,2,3,4], 2) = [[1,2], [3,4-]];
the chunk ([1,2,3,4,5], 2) = [[ 1,2], [3,4], [5]];

Copy the code
 
function chunk(arr, size) {
  var newarr=[];
  for(var i=0;i<arr.length;i+=size) {
    var brr=arr.slice(i,i+size);
    newarr.push(brr);
  }
  return newarr;
}

chunk(["a", "b", "c", "d"], 2);
 
Copy the code

 

11, returns an array of truncated nelements remaining after the further element, truncation starting with index 0.

Copy the code
 
Slasher function (ARR, howMany) { 
  var len = arr.length; 
    IF (howMany === 0) { 
      return ARR; 
    } the else { 
      return arr.splice (howMany, len); 
// return value is deleted } } Slasher ([1, 2, 3], 2);
// results: [3]

// splice()method to replace the old elements with new elements, in order to modify the contents of the array.
 语法:arrayObject.splice(index,howmany,item1,.....,itemX)

  parameter

start​: Which one from the array to start modifying content. If you exceed the length of the array, from the end of the array start adding content; if it is negative, it means the first of several array from the beginning of the last one.
deleteCount: Integer representing the number of array elements to be removed. If  deleteCount  is 0, no elements removed. In this case, at least you should add a new element. If  deleteCount  greater than the start  total number of elements of the following, from  start  the back of the elements will be deleted (including the first  start  place).
itemN: To add an element into the array. If not specified, then  splice()  only delete the array elements.

  Returns: an array of elements to be deleted composition. If you delete only one element of the array contains only one element is returned. If you do not remove elements, an empty array is returned.

 
 
 
Copy the code

 

12, if the first array element contains a string of the second character string of all the elements, the function returns true.

    For example, ["hello", "Hello"]it should return true, because in the case of ignoring case, all of the characters of the second string can be found in the first string.

Copy the code
 
mutation function (ARR) { 
  var aStr ARR = [0] .toLowerCase (); 
  var BSTR ARR = [. 1] .toLowerCase (); 
  for (var I = 0; I <bstr.length; I ++) { 
    IF (aStr. the indexOf (BSTR [I]) == -1) { 
      return to false; 
    } the else { 
      return to true; 
    } 
  } 
} 

mutation ([ "Hello", "Hey"]); 
// results: to true

// indexOf() method returns the specified value the position of the first occurrence of the string object. From the  fromIndex beginning to find the location, and if not, -1 is returned.
stringObject.indexOf(searchvalue,fromindex)

parameter

searchValue: A string representation of the value being sought.
fromIndex: Optional string that indicates the position of calling the method begin the search. It can be any integer. The default value is 0. If  fromIndex < 0 the entire string to find (as pass into 0). If  fromIndex >= str.length, then the method returns -1, unless the search string is a null string, then return str.length.

Case-sensitive  indexOf method is case-sensitive. For example, the following expression -1:

"Blue Whale".indexOf("blue") // returns -1

Detecting whether there is a character string when the character string is detected whether a string is present in the other, use the following method:

"Blue Whale".indexOf("Blue") !== -1; // true
"Blue Whale".indexOf("Bloe") !== -1; // false
 
Copy the code

 

13, all false values ​​to delete the array.

   In JavaScript, false values are false, null, 0, "", undefined and  NaN.

Press Ctrl + C to copy the code
Press Ctrl + C to copy the code

 

 

After reading, if you have confidence, you can challenge yourself.

http://www.w3cschool.cn/codecamp/list?ccid=8

Guess you like

Origin www.cnblogs.com/devanwu/p/10955735.html