Home  >  Article  >  Web Front-end  >  Summary of the introduction to array objects in JavaScript

Summary of the introduction to array objects in JavaScript

零下一度
零下一度Original
2017-06-26 09:07:341210browse

Array object is an array object used to store multiple values ​​​​in a single variable. JS arrays are weakly typed, so the array is allowed to contain elements of different types. The array elements can even be objects or other arrays.

  • Syntax for creating an array

1. Array constructor

1、var list=new Array();2、var list=new Array(size);3、var list=new Array(element0,element1,...elementn);

2. Literal method

var Array[element0,element1,...elementn];

For example

var list=new Array(1,true,null,undefined,{x:1},[1,2,3]);
var list[1,true,null,undefined,{x:1},[1,2,3]];
  • Classification of arrays

1. Two-dimensional array. The essence of a two-dimensional array is that the elements in the array are is an array.

var arr = [[1,2],[a,b]];
alert(arr[1][0]); //a 第2列第1行所在的元素

2. Sparse array

A sparse array is an array containing discontinuous indexes starting from 0. In sparse arrays, the length attribute value is generally larger than the actual number of elements (uncommon)
Example
var a=["a",,"b",,,,"c",,] ;

  • Array object properties

Properties Function
length attribute Represents the length of the array, that is, the number of elements in it
prototype attribute Returns a reference to the prototype of the object type
constructor attribute Represents the function that creates the object

1. Length attribute

Explain the length attribute through some operations
var arr=[1,2,3,4,5,6,7,8, 9,10];//Defines an array containing 10 numbers.
The length attribute of the array is variable

alert(arr.length); //显示数组的长度10
arr.length=15; //增大数组的长度,length属性是可变的
alert(arr.length); //显示数组的长度已经变为15

Accessing the array elements

alert(arr[3]); //显示第4个元素的值,为4

Reduce the array length

arr.length=2; //将数组的长度减少到2,数组中的元素只剩下索引值小于2的元素
alert(arr[9]); //这时候显示第10个元素已经变为"undefined"因为索引值大于等于2的元素都被抛弃了

Restore the array length

arr.length=10; //将数组长度恢复为10
alert(arr[9]); //长度恢复之后已经抛弃的元素却无法收回,显示"undefined"

2. Prototype attribute

prototype The attribute returns a reference to the prototype of the object type. prototype attributes are common to object.
objectName.prototype
objectName The parameter is the name of the object object.

Description: Use the prototype property to provide a set of basic functions of the object's class. New instances of an object "inherit" the operations assigned to the object's prototype.

For array objects, use the following example to illustrate the use of the prototype attribute.
Add a method to the array object to return the maximum element value in the array. To accomplish this, declare a function, add it to Array.prototype, and use it.

function array_max( )
{   var i, max = this[0];   for (i = 1; i < this.length; i++)
   {       if (max < this[i])
       max = this[i];
   }   return max;
}Array.prototype.max = array_max;var x = new Array(1, 2, 3, 4, 5, 6);var y = x.max( );

After this code is executed, y holds the maximum value in the array x, or say 6.

3. Constructor attribute

The constructor attribute represents the function that creates the object.
object.constructor //object is the name of the object or function.
Description: constructor properties are members of all objects with prototype. They include all JScript intrinsic objects except Global and Math objects. The constructor attribute holds a reference to the function that constructs a specific object instance.

For example:

x = new String("Hi");if (x.constructor == String) // 进行处理(条件为真)。//或function MyFunc {// 函数体。
}

y = new MyFunc;if (y.constructor == MyFunc) // 进行处理(条件为真)。

For array:

y = new Array();
  • Object method of Array

Description : Part of it is a new feature of ECMAScript5 (not supported by IE678)

##toSource()Return the source code of the objecttoString ()Convert the array into a string and return the resulttoLocalString()Convert the array into a local element and return the resultunshiftAdd one or more elements to the beginning of the array and return the new lengthvalueof()Return the original value of the array object##forEach()map()##filter()FilterCheck and judgeCheck and judgepairs Perform certain operationsPerform operations from right to leftArray retrieval to find an elementDetermine whether it is an array
Method Function
concat() Concatenate two or more arrays and return the result
join() Group the elements of the array Start a string
pop() Delete and return the last element of the array
push() Add one or more elements to the end of the array and return the new length
reverse Reverse the order of the elements in the array
shift() Delete and return the first element of the array
slice() From an existing array Return the selected elements
sort() Sort the array elements
splice() Delete elements and add new elements to the array
Traverse the array object
Do some mapping to the array
##every()
some()
reduce()
reduceRight()
indexOf()
Array.isArray([])

主要对一些新特性进行讲解
concat
concat作用是拼接数组,需要注意的是也可以把一个数组元素作为拼接的元素,如果这样的话,数组会被拉平,再和其它的元素拼接起来成为新的数组,但是不会被拉平两次,concat不会修改原数组。
例如

var arr=[1,2,3,4,5];
arr.concat([10,11],13);//[1,2,3,4,5,10,11,13]
arr.concat([1,[2,3]]);//[1,2,3,4,5,1,[1,3]]

slice
slice(a,b)a和b可以取负数,表示从a位置开始截取到b位置的一段数组,是一个左闭右开的区间,a和b可以取负数,如果是负数代表倒数第a/b个元素

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

splice
splice删除元素并向数组添加新元素
object.splice(a)从左边开始删除a个元素
object.splice(a,b)从a位置开始截取其中的b个元素
object.splice(a,b,c,d)从a位置开始截取b个元素,并将c和d或者更多的元素插入原数组
需要注意的是splice会修改原数组

var arr=[1,2,3,4,5];
arr.splice(2);//[3,4,5]
arr;//[1,2];原数组被修改了

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

var arr=[1,2,3,4,5];
arr.splice(1,1,‘a’,‘b’);//[2]
arr;//[1,"a","b",3,4,5];

foreach
foreach()函数从头到尾把数组遍历一遍。有三个参数分别是:数组元素,元素的索引,数组本身

var arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a)
{//分别对应:数组元素,元素的索引,数组本身console.log(x + &#39;|&#39; + index + &#39;|&#39; + (a === arr));
});// 1|0|true// 2|1|true// 3|2|true// 4|3|true// 5|4|true

说明:如果只有一个参数那这个参数代表数组元素,也就是数组的值,请看例2。

例2
var data=[1,2,3,4,5,6];
var sum=0;
data.forEach(function(v){//其中的v就是数组的值 123456
sum+=v;})
document.write(sum+"<br>");//打印出来是21

map 
map 对数组做一些映射,map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组,它与forEach的区别是forEach为数组中的每个元素执行一次回调函数。

var arr = [1, 2, 3];
arr.map(function(x) {     return x + 10;
}); // [11, 12, 13]
arr; // [1, 2, 3]

filter
filter 过滤掉某些元素,和map有点类似,Array的filter也接收一个函数。但是和map不同的是, filter把传入的函数依次作用于每个元素,然后根据返回值是 true 还是false决定保留还是丢弃该元素,也就是过滤掉不符合要求的某些元素。

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.filter(function(x, index) {
     return index % 3 === 0 || x >= 8;
}); // returns [1, 4, 7, 8, 9, 10]
arr; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

every()与some()
every()与some()方法都是JS中数组的迭代方法。every()是对数组中的每一项运行给定函数,如果该函数对每一项返回true,则返回true。some()是对数组中每一项运行指定函数,如果该函数对任一项返回true,则返回true。
总结就是every()当每个元素都符合条件的时候返回true,而some()是任一项满足条件就返回true

例1 every()var arr = [1, 2, 3, 4, 5];
arr.every(function(x) {     return x < 10;
}); // true

arr.every(function(x) {     return x < 3;
}); // false

some只需要有一个符合的就行

例2 somevar arr = [1, 2, 3, 4, 5];
arr.some(function(x) {     return x === 3;
}); // true

arr.some(function(x) {     return x === 100;
}); // false

reduce()
Array的reduce()把一个函数作用在这个Array的[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果就是:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
var arr = [1, 2, 3];var sum = arr.reduce(function(x, y) {     return x + y
}, 0); //参数 0是可选的,如果写了参数0那第一次传递的两个值就是0和1
如果不写第一次传递的就是数组的前两个值,计算结果是6
arr; //[1, 2, 3]

arr = [3, 9, 6];var max = arr.reduce(function(x, y) {     console.log(x + "|" + y);     return x > y ? x : y;
});// 3|9// 9|6
max; // 9

reduceRight
和reduce一样只不过reduceRight 变成了从右到左两两执行某些操作

max = arr.reduceRight(function(x, y) {
     console.log(x + "|" + y);     return x > y ? x : y;
});// 6|9// 9|3max; // 9

indexOf()
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置,indexOf(a,b)表示查找a元素,从b位置开始;lastindexOf表示从右向左找。当b为负数的时候表示从倒数第几个元素开始找,请看例子。

var arr = [1, 2, 3, 2, 1];
arr.indexOf(2); // 1
arr.indexOf(99); // -1表示没有这个元素
arr.indexOf(1, 1); // 4
arr.indexOf(1, -3); // 4查找1从倒数第3个元素开始
arr.indexOf(2, -1); // -1查找2从倒数第1个元素开始
arr.lastIndexOf(2); // 3从右边开始找第一次出现2的位置
arr.lastIndexOf(2, -2); // 3从右边的倒数第二个开始找2出现的位置
arr.lastIndexOf(2, -3); // 1

isArray
isArray用来判断是否是数组,但是isArray是Array构造器对象上的属性,所以不能直接用isArray,必须要写成Array.isArray([]),但是可以其它的判断方法直接判断

[]instanceof Array;//true
({}).toString.apply([])===&#39;[object Array]&#39;;//true
[].construcror===Array;//true

数组和一般对象的比较

  数组 / 一般对象
相同点 都可以继承,对象不一定是数组,都可以当做对象添加属性
不同点 数组自动更新length按索引访问数组比访问一般对象属性明显迅速。数组对象继承Array.prototype上的大量数组操作方法

数组和字符串的比较

 

  数组 /字符串
相同点 字符串是数组的一种
不同点 字符串是不可变的数组,字符串没有数组的方法

学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入学习交流 

The above is the detailed content of Summary of the introduction to array objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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