Home > Web Front-end > JS Tutorial > body text

Summary of common methods for js arrays and strings

高洛峰
Release: 2017-01-14 11:37:14
Original
1092 people have browsed it

Recently I am sorting out the basics of js, starting with arrays and strings.

string Commonly used methods:

1.substring (start starting position index, end ending position index) The intercepted position does not include the characters at the end position. Just write one parameter to indicate interception from the starting position. At the end

var str='abcdefg'; 
str.substring(1) //得到bcdefg  str.substring(1,3) //得到bc
Copy after login

When entering a negative value, the negative value will be changed to 0, whichever is smaller will be used as the starting position

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

2.slice(start starting position index, end (end position index) is basically similar to substring, the difference is that the parameter is a negative number.

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

When entering a negative value, 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) / When the absolute value of /f

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, return ''

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

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

When a negative value is entered, the start parameter is added to the length of the string, and when the end is negative, the parameter becomes 0

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

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

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

5.index(string) Returns the first occurrence of a subcharacter in the String object string position. If the substring is not found, -1 is returned.

var str='abcdefga' str.indexOf('a') // 0 str.indexOf('h') //-1

6.lastIndexOf(string) Flashback search

Returns the position of the first substring occurrence in the String object. If the substring is not found, -1 is returned.

var str='abcdefga' str.lastIndexOf('a') // 7

7.split(str) Split the string into an array based on parameters

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

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

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

10.match() – This method can search for a specified value within a string, or find a match for one or more regular expressions.

11.search Method returns the same as regular expression search The position of the first string whose content matches.

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

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

Commonly used methods for arrays

1. push Add to the end Return the added array

2. Unshift Add to the front Return the added array

3. shift Delete (from the front) Return the processed array

4. pop Delete the last item Return the processed array

5. reverse Array flip Return the processed array

6. join Convert array into string

var arr=[1,2,3,4,5], str=arr.join('--');
 console.log(str); // 1--2--3--4--5 以join内的参数切割数组
 console.log(arr); // [1,2,3,4,5]  原数组未变
Copy after login

7. slice(start,end) Intercept array from start (start) to end (end not included)

Return to the new array, the original array is 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]
Copy after login

8. Concat array merged

9. Splice Array

(1). One parameter. Intercept the parameter position and fill in the negative number, similar to the str slice above. Return the intercepted array. The original array changes

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]
Copy after login

(2). Two Parameter interception (starting position, number) Return the intercepted array Original array change

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()
Copy after login

(3).Add Original array increase

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

(4). Replacement

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)
Copy after login

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

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

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

There is a problem when jumping out of a nested loop, which has not been solved yet;

11. map Methods Mapping 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;
   })
Copy after login

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]
Copy after login

By default the sort method is Sorted in ascii alphabetical order, not sorted by numerical size as we think

arr.sort(function(a,b){ return a-b})

a-b从小到大 b-a从大到小

13. 顺便写写我知道的排序方法

(1)冒泡排序 每次比较相邻的两个数,如果后一个数比前一个数小,换位置

function bSort(arr){
    var tmp;
    for(var i=0,len=arr.length-1;i<len;i++){
      for(var j=0;j<len;j++){
        if(arr[j]>arr[j+1]){
          //换位置
          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]){
          //换位置
          tmp = arr[i + 1];
          arr[i + 1] = arr[i];
          arr[i] = tmp;
        }
      })
    })
    return arr
  }
Copy after login


(2)快速排序 二分法,找到中间的数,取出来(新数组),原数组没,每次和此数比较,小的放到左边,大的放到右面

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<c[0]){
           left.push(item);
         }else{
           right.push(item);
         }
       })
    return fastSoft(left).concat(c,fastSoft(right));
  }
Copy after login

14. 数组的去重也写下吧

(1)双层循环不是很好

var arr=[2,3,2,2,2,4,5],
      arr2=[];
        function find(arr2,ele){
         for(var i= 0,len=arr2.length;i<len;i++){
           if(arr2[i]==ele) return true;
         }
          return false;
        }
        for(var i= 0,len=arr.length;i<len;i++){
          if(!find(arr2,arr[i])){
            arr2.push(arr[i]);
          }
        }
Copy after login

(2)利用json的key值无重复

var arr=[2,3,2,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));//类型发生变化了
          }
Copy after login

(3) 利用sort方法排序,去掉旁边相同项

var arr=[2,3,2,4,4,4,5],
   arr2=[];
     arr.sort();
     for(var i=0;i<arr.length;i++){
       if(arr[i]==arr[i+1]){
         arr.splice(i--,1);
       }
     }
Copy after login


一些常见数学方法

    math.abs() 取绝对值  math.ceil() 向上取整 math.floor() 向下取整
    math.round() 四舍五入 math.roundom
function getRan(n,m){
  return Math.floor(Math.random()*(m-n)+n);
}
Copy after login

数组和字符串的一些综合应用

1. 截取后缀名

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

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

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

var arr=str.split(&#39;.&#39;);
console.log(arr[arr.length-1]);
Copy after login

2.字母翻转,首字母大写

var str=&#39;wo shi yi ge demo&#39;,
   arr=str.split(&#39; &#39;);
   for(var i=0;i<arr.length;i++){
     console.log()
    arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].substring(1);
   }
   arr.reverse();
   str=arr.join(&#39; &#39;);
Copy after login

3. str中字符出现次数的统计

var str=&#39;aaaandkdffsfsdfsfssq12345&#39;,
   json={},
   n= 0,
   sName;
   for(var i= 0,len=str.length;i<len;i++){
     var Letter=str.charAt(i);
     //统计次数
     if(json[Letter]){
       json[Letter]++;
     }else{
       json[Letter]=1;
     }
   }
   //找最大
   for(var name in json){
     if(json[name]>n){
       n=json[name];
       sName=name;
     }
   }
   console.log(&#39;出现最多的字母&#39;+sName+&#39;次数为&#39;+n);
Copy after login

4. 简单的url参数解析

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHP中文网!

更多js数组与字符串常用方法总结相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!