Home > Web Front-end > JS Tutorial > Commonly used methods for writing arrays

Commonly used methods for writing arrays

一个新手
Release: 2017-09-18 10:48:57
Original
2189 people have browsed it

Arrays and strings are the two most commonly used sections in js. Therefore, it is necessary to master these two commonly used methods proficiently.

1.2.3.4 These four methods directly modify the original array

   1.unshift(参数1,参数2,,,) 
  **不会创建新数组 在数组最前面插入。返回新数组的长度。 
  2.shift() 把数组最前面的一个删除,返回删除的那个元素 
  3.push(参数1,参数2,,,) 
  **不会创建新数组 在数组的最后面插入。返回新数组的长度 
  4.pop() 
  **把数组的最后一项删除,并把它返回
  5.splice(index,number,arr1,arr2,arr3,,,,)
Copy after login

Note::: This method will directly Modify the array

这个方法有三种用途1.删除2.增添3.修改
根据所传递的参数的不同用途不一样
index(必须):整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。number(必须):要删除的项目数量。如果设置为 0,则不会删除项目
arr1,arr2,,,(可选)向数组添加的新项目。
Copy after login

6.slice(start,end)
Note::: This method does not modify the array, but returns a subarray

和字符串一样,从数组里面下标start开始,到end结束(包含start,不包含end)
Copy after login

7.sort() sorts the elements of the array

arr.sort(sortArr)    
function sortArr(a,b){return  a-b}    从小到大排序。function sortArr(a,b){return  b-a}    从大到小排序。
如果需要随机排序的话可以使用function sortArr(){return  Math.random-0.5}
Copy after login

8.join() method

将数组每一项都变成字符串。并使用指定的分割符连接起来。默认是,号
指定的分隔符写在括号里面。
Copy after login

The above is the detailed content of Commonly used methods for writing arrays. For more information, please follow other related articles on the PHP Chinese website!

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