JS常用处理数组的方法

JavaScript013

JS常用处理数组的方法,第1张

一、概述

join( ) ————————数组转字符串

split( ) ———————–字符串转数组

push( ) ———————-将数据添加到数组尾部

pop( ) ———————–数组末尾移除最后一项

shift( ) ———————–删除原数组第一项

unshift( ) ——————–将数据添加到数组头部

sort( ) ————————按升序排列数组项

reverse( ) ——————–反转数组项的顺序

concat( ) ——————–多个数组合并,原数组不变

slice( ) ———————–返回开始下标到结束下标之间的项组成的新数组,原数组不变

splice( ) ———————-从数组中添加/删除项目,然后返回被删除的项目,改变原数组

二、定义和用法

1、join()

2、concat()

3、pop()

4、shift()

5、push()

6、unshift()

7、reverse()

8、slice()

9、splice()

10、toString()

11、sort()

12、includes()

13、forEach()

14、map()

JavaScript由于是弱类型,因此数组元素没有固定类型,而是直接使用Array构造器声明。

使用 new 运算符和 Array() 构造器 生成一个新的数组,如下面的示例。

var theMonths = new Array(12)

theMonths[0] = "Jan"

theMonths[1] = "Feb"

theMonths[2] = "Mar"

theMonths[3] = "Apr"

theMonths[4] = "May"

theMonths[5] = "Jun"

theMonths[6] = "Jul"

theMonths[7] = "Aug"

theMonths[8] = "Sep"

theMonths[9] = "Oct"

theMonths[10] = "Nov"

theMonths[11] = "Dec"

数组下标可以被认为是对象的属性,它是通过数字索引来引用的。注意添加到数组中的已命名的属性不能通过数字来索引;它们是与数组元素分离的。

用关键字 Array 生成数组时,Jscript 包含了 length 属性,该属性记录了数组入口数。如果没有给该属性指定值,则设置长度为 0 且数组没有入口点。如果指定一个数值,则将长度设置为该数。如果指定了不止一个参数,则这些参数被用作数组的入口。另外,参数的数目被赋给 length 属性。如下面的示例与前一个示例是等价的。

var theMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",

"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")