Summary of common js array and string Methods

Source: Internet
Author: User
Tags first string string methods
This article mainly summarizes common methods of js arrays and strings. It has some reference value. Let's take a look at the basics of js recently, starting with arrays and strings.

Common Methods for string:

1. substring (index at the start of start, index at the end of end) the truncated position does not contain the character at the end position. Only one parameter is written to indicate that the string is truncated from the start position to the end.

Var str = 'abcdefg'; str. substring (1) // obtain bcdefg str. substring (1, 3) // obtain bc

When a negative value is input, the negative value is changed to 0. Which smaller value is used as the start position?

Str. substing (-) => str. substring () //
Str. substring (1,-2) => str. substring (0, 1) //

2. slice (index at the start and end locations) is similar to substring in that the parameter is negative.

var str='abcdefg';str.slice(1)  //bcdefg      str.substring(1,3) // bc

When a negative value is input, the value is added to the length of the string.

Str. slice (-1) => str. slice (6) // g
Str. slice (1,-2) => str. slice (1, 5) // bcde
Str. slice (-2,-1) => str. slice (5, 6) // f

When the absolute value is greater than the length of the string, it becomes 0.

Str. slice (-22) => str. substring (0) // abcdefg

When the absolute value of the second parameter is greater than the length of the string, ''is returned''

3. substr (start position index, number of characters to be returned by end)

var str='abcdefg';str.substr(1) //bcdefg      str.substr(1,1) //b

When a negative value is input, the start parameter is added to the string length. When the end value is negative, the start parameter is 0.

str.substr(-1) =>str.substr(6)//g        str.substr(-2,-3) // ''

4. The charAt (index) method returns the characters at the specified index position. If the index value exceeds the valid range (0 minus the string length), an empty string is returned.

var str='abcdefg';str.charAt(2) // c

5. index (string) returns the position of the substring that appears for the first time in the String object. If no substring is found,-1 is returned.

Var str = 'abcdefga 'str. indexOf ('A') // 0 str. indexOf ('H') //-1

6. lastIndexOf (string) Reverse Lookup

Returns the position of the substring that appears for the first time in the String object. If no substring is found,-1 is returned.

Var str = 'abcdefga 'str. lastIndexOf ('A') // 7

7. split (str) Splits strings into arrays by Parameters

Var str = 'abcadeafg' str. split ('A') // ["", "bc", "de", "fg"]

8. The toLowerCase method returns a string in which letters are converted to lowercase letters.

9. The toUpperCase method returns a string in which all letters are converted to uppercase letters.

10. match ()-the method can retrieve the specified value in a string, or find matching of one or more regular expressions.

11. The search method returns the position of the first string matching the regular expression search content.

12. replace is used to find a string that matches a regular expression, and then replace it with a new string.

Http://www.cnblogs.com/bijiapo/p/5451924.html

Common array Methods

1. Add push to the end to return the added Array

2. Add unshift to the beginning to return the added Array

3. shift Delete (from the Front) returns the processed Array

4. pop deletes the last returned array.

5. reverse the reverse array and return the processed array.

6. Convert the join array to a string

Var arr = [1, 2, 4, 5], str = arr. join ('--'); console. log (str); // 1--2--3--4--5 cut the array console with parameters in the join. log (arr); // [1, 2, 3, 4, 5] The original array has not changed.

7. slice (start, end) intercepts the array from start (start) to end (end does not contain)

Returns a new array. The original array remains unchanged.

var arr=[1,2,3,4,5],new=arr.slice(2,4);console.log(new);  // [3,4]console.log(arr);  // [1,2,3,4,5]

8. concat array Merging

9. splice (start subscript, number, ele1, ele2......) Cut Array

(1). A parameter is truncated from the parameter position and a negative number is entered. Similar to the preceding str slice, the original array of the intercepted array changes are returned.

var arr=[1,2,3,4,5];console.log(arr.splice(1));  // [2,3,4,5]console.log(arr);       // [1]console.lgo(arr.splice(-1))  // [5]

(2). Two parameters are truncated (start position, number), and the original array changes are returned.

var arr=[1,2,3,4,5];console.log(arr.splice(1,3)); // [2,3,4]console.log(arr)       // [1,5]arr.splice(0,1) =>arr.shift()arr.splcie(arr.length-1,1) =>arr.pop()

(3). Add the original array

var arr=[1,2,3,4,5];console.log(arr.splice(1,0,13)); // []console.log(arr);        // [1,13,2,3,4,5]

(4). Replace

var arr=[1,2,3,4,5];console.log(arr.splice(1,2,'a','b')) // [2,3]console.log(arr);        // [1,'a','b',4,5]arr.splice(0,0,1) =>arr.unshift(1);arr.splice(arr.length,0,1) => arr.push(1)

10. arr. forEach (item, index, array) {} traversal, loop similar to jquery's each

The item parameter is the content in the array, and index is its index. array indicates the array itself.

var arr=[1,2,3,4,5];      arr.forEach(function(item,index,array){      })

The nested Jump Out Loop is encountered and is not resolved yet;

11. map Method ing usage is similar to forEach

var men=[       {'name':1,'age':12},       {'name':2,'age':22},       {'name':3,'age':33}   ],   age=men.map(function(item){       return item.age;   })

12. arr. sort sorting

var arr=[1,2,22,11,33,3,5,4];  console.log(arr.sort()) // [1,11,2,22,3,33,4,5]

By default, the sort method is sorted by ascii letters, rather than by numbers.

Arr. sort (function (a, B) {return a-B })

A-B from small to Big B-a from large to small

13. Write the sorting method I know by the way.

(1) Bubble Sorting compares two adjacent numbers each time. If the last number is smaller than the previous one, change the position.

Function bSort (arr) {var tmp; for (var I = 0, len = arr. length-1; I
 
  
Arr [j + 1]) {// change location tmp = arr [j + 1]; arr [j + 1] = arr [j]; arr [j] = tmp ;}}return arr;} function bSort (arr) {var tmp; arr. forEach (function (item, I) {arr. forEach (function (item, I) {if (item> arr [I + 1]) {// change location tmp = arr [I + 1]; arr [I + 1] = arr [I]; arr [I] = tmp ;}}) return arr}
 


(2) Fast sort binary method. Find the number in the middle and obtain it (new array). The original array does not exist. Each time it is compared with this number, the small one is placed on the left, and the big one is placed on the right.

Function fastSoft (arr) {var len = arr. length; if (len <= 1) {return arr} var cIndex = Math. floor (len/2), c = arr. splice (c, 1), left = [], right = []; arr. forEach (function (item, I) {if (item
 
  

14. Write down the deduplication of the array.

(1) the double-layer loop is not very good.

Var arr = [2, 3, 2, 2, 4, 5], arr2 = []; function find (arr2, ele) {for (var I = 0, len = arr2.length; I
   
    

(2) No duplicate key values using json

Var arr = [2, 3, 2, 2, 4, 5], json = {}, arr2 = []; arr. forEach (function (item, I) {if (! Json [item]) {json [item] = 222 ;}}); for (var name in json) {arr2.push (Number (name); // The type has changed}

(3) sort using the sort method to remove the same item next to it

Var arr = [2, 3, 2, 4, 4, 5], arr2 = []; arr. sort (); for (var I = 0; I


Some common mathematical methods

Math. abs () obtains the absolute value math. ceil () rounded up to math. floor () rounded down to math. round () rounded to math. roundomfunction getRan (n, m) {return Math. floor (Math. random () * (m-n) + n );}

Comprehensive application of arrays and strings

1. truncate the suffix

(1) var str = '1. xxx. avi ';

Str = str. substring (str. lastIndexOf ('.') + 1 );

(2) var str = '1. xxx. avi ';

var arr=str.split('.');console.log(arr[arr.length-1]);

2. letter flip, uppercase letters

Var str = 'Wo shi yi ge demo', arr = str. split (''); for (var I = 0; I

3. Statistics on the number of occurrences of characters in str

Var str = 'aaaandkdffsfsdfsfssq12345 ', json ={}, n = 0, sName; for (var I = 0, len = str. length; I
       
        
N) {n = json [name]; sName = name ;}} console. log ('the most frequently seen letters '+ sName +' are '+ n );
       

4. Simple url Parameter Parsing

function getData() {        var search = window.location.search.substring(1);        if (!search) {          return;        }        var arr = search.split('&'),            arr2 = [],            json = {},            key,            alue;        for (var i = 0; i < arr.length; i++) {          arr2 = arr[i].split('=');          key = arr2[0];          value = arr2[1];          json[key] = value;        }        return json;       }

The above is all the content of this article. I hope this article will help you in your study or work, and I also hope to support PHP!

For more articles on js array and string common methods, please refer to PHP Chinese network!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.