An array is a set of values arranged in order. In contrast, the property names of objects are unordered. Essentially, arrays use numbers as lookup keys, while objects have user-defined property names. JavaScript does not have a real associative array, but objects can be used to implement associated functions
Array() is just a special type of Object(), that is, an Array() instance basically has Object() instance with some extra functionality. Arrays can save any type of values, which can be updated or deleted at any time, and the size of the array is dynamically adjusted.
In addition to objects, the Array type may be the most commonly used type in JavaScript. Moreover, arrays in JavaScript are quite different from arrays in most other languages. This article will introduce the array Array type in javascript
Creating an array
There are two ways to create an array: using literal syntax and using the Array() constructor
【Literal】
Using array literal Quantity is the simplest way to create an array. Just separate the array elements with commas in square brackets
var empty = []; //没有元素的数组 var primes = [2,3,5,7,11]; //有5个数值的数组
Although javascript arrays are different from arrays in other languages They are all ordered lists of data, but unlike other languages, each item of a JavaScript array can save any type of data
var misc = [1.1,true, "a"]; //3个不同类型的元素
Array literal The values in do not have to be constants, they can be any expression
var base = 1024; var table = [base,base+1,base+2,base+3];
It can contain object literals or other array literals
var b = [ [1,{x:1,y:2}],[2,{x:3,y:4}] ];
If the elements of the array are still arrays, a multi-dimensional array is formed
var a = [[1, 2], [3, 4]];
[Note] Use numbers In literal representation, the Array constructor will not be called
[Constructor]
There are three ways to call the constructor
【1】Without parameters, create an empty array
//该方法创建一个没有任何元素的空数组,等同于数组直接量[] var a = new Array();
【2】There is a numeric parameter, which is used to specify the length of the array
var a = new Array(10); console.log(a);//[] console.log(a[0],a.length);//undefined 10
[Note] If there is a parameter of other types, an array with only one item containing that value will be created
var a = new Array('10'); console.log(a);//['10'] console.log(a[0],a.length);//10 1
[3] When there are multiple parameters, the parameters are expressed as specific elements of the array
var a = new Array(1,2,3); console.log(a);//[1,2,3] console.log(a[0],a[1],a[2]);//1 2 3
Use Array() When constructing a function, you can omit the new operator
##
var a1 = Array(); var a2 = Array(10); var a3 = Array(1,2,3); console.log(a1,a2,a3);//[] [] [1,2,3]
The essence of array
typeof [1, 2, 3] // "object"
var arr = ['a', 'b', 'c']; console.log(Object.keys(arr));// ["0", "1", "2"] var obj = { name1: 'a', name2: 'b', name3: 'c' };
o={}; //创建一个普通的对象 o[1]="one"; //用一个整数来索引它 //数值键名被自动转成字符串 var arr = ['a', 'b', 'c']; arr['0'] // 'a' arr[0] // 'a'
var a = []; //索引 a['1000'] = 'abc'; a[1000] // 'abc' //索引 a[1.00] = 6; a[1] // 6
[Note] A single value cannot be used as an identifier. Therefore, array members can only be represented by square brackets
var arr = [1, 2, 3]; arr[0];//1 arr.0;//SyntaxError
var a = [1,2,3]; //属性名 a[-1.23]=true; console.log(a.length);//3 //索引 a[10] = 5; console.log(a.length);//11 //属性名 a['abc']='testing'; console.log(a.length);//11
Array length
[].length //=>0:数组没有元素 ['a','b','c'].length //=>3:最大的索引为2,length为3
[,,,].length; //3 (Array(10)).length;//10 var a = [1,2,3]; console.log(a.length);//3 delete a[1]; console.log(a.length);//3
var arr = ['a', 'b']; arr.length // 2 arr[2] = 'c'; arr.length // 3 arr[9] = 'd'; arr.length // 10 arr[1000] = 'e'; arr.length // 1001
【2】设置length属性为小于当前长度的非负整数n时,当前数组索引值大于等于n的元素将从中删除
a=[1,2,3,4,5]; //从5个元素的数组开始 a.length = 3; //现在a为[1,2,3] a.length = 0; //删除所有的元素。a为[] a.length = 5; //长度为5,但是没有元素,就像new
【3】将数组的length属性值设置为大于其当前的长度。实际上这不会向数组中添加新的元素,它只是在数组尾部创建一个空的区域
var a = ['a']; a.length = 3; console.log(a[1]);//undefined console.log(1 in a);//false
如果人为设置length为不合法的值(即0——232-2范围以外的值),javascript会报错
// 设置负值 [].length = -1// RangeError: Invalid array length // 数组元素个数大于等于2的32次方 [].length = Math.pow(2,32)// RangeError: Invalid array length // 设置字符串 [].length = 'abc'// RangeError: Invalid array length
由于数组本质上是对象,所以可以为数组添加属性,但是这不影响length属性的值
var a = []; a['p'] = 'abc'; console.log(a.length);// 0 a[2.1] = 'abc'; console.log(a.length);// 0
数组遍历
使用for循环遍历数组元素最常见的方法
var a = [1, 2, 3]; for(var i = 0; i < a.length; i++) { console.log(a[i]); }
当然,也可以使用while循环
var a = [1, 2, 3]; var i = 0; while (i < a.length) { console.log(a[i]); i++; } var l = a.length; while (l--) { console.log(a[l]); }
但如果数组是稀疏数组时,使用for循环,就需要添加一些条件
//跳过不存在的元素 var a = [1,,,2]; for(var i = 0; i < a.length; i++){ if(!(i in a)) continue; console.log(a[i]); }
还可以使用for/in循环处理稀疏数组。循环每次将一个可枚举的属性名(包括数组索引)赋值给循环变量。不存在的索引将不会遍历到
var a = [1,,,2]; for(var i in a){ console.log(a[i]); }
由于for/in循环能够枚举继承的属性名,如添加到Array.prototype中的方法。由于这个原因,在数组上不应该使用for/in循环,除非使用额外的检测方法来过滤不想要的属性
var a = [1,,,2]; a.b = 'b'; for(var i in a){ console.log(a[i]);//1 2 'b' } //跳过不是非负整数的i var a = [1,,,2]; a.b = 'b'; for(var i in a){ if(String(Math.floor(Math.abs(Number(i)))) !== i) continue; console.log(a[i]);//1 2 }
javascript规范允许for/in循环以不同的顺序遍历对象的属性。通常数组元素的遍历实现是升序的,但不能保证一定是这样的。特别地,如果数组同时拥有对象属性和数组元素,返回的属性名很可能是按照创建的顺序而非数值的大小顺序。如果算法依赖于遍历的顺序,那么最好不要使用for/in而用常规的for循环
有三个常见的类数组对象:
【1】arguments对象
// arguments对象 function args() { return arguments } var arrayLike = args('a', 'b'); arrayLike[0] // 'a' arrayLike.length // 2 arrayLike instanceof Array // false
【2】DOM方法(如document.getElementsByTagName()方法)返回的对象
// DOM元素 var elts = document.getElementsByTagName('h3'); elts.length // 3 elts instanceof Array // false
【3】字符串
// 字符串 'abc'[1] // 'b' 'abc'.length // 3 'abc' instanceof Array // false
[注意]字符串是不可变值,故当把它们作为数组看待时,它们是只读的。如push()、sort()、reverse()、splice()等数组方法会修改数组,它们在字符串上是无效的,且会报错
var str = 'abc'; Array.prototype.forEach.call(str, function(chr) { console.log(chr);//a b c }); Array.prototype.splice.call(str,1); console.log(str);//TypeError: Cannot delete property '2' of [object String]
数组的slice方法将类数组对象变成真正的数组
var arr = Array.prototype.slice.call(arrayLike);
javascript数组方法是特意定义为通用的,因此它们不仅应用在真正的数组而且在类数组对象上都能正确工作。在ECMAScript5中,所有的数组方法都是通用的。在ECMAScript3中,除了toString()和toLocaleString()以外的所有方法也是通用的
var a = {'0':'a','1':'b','2':'c',length:3}; Array.prototype.join.call(a,'+');//'a+b+c' Array.prototype.slice.call(a,0);//['a','b','c'] Array.prototype.map.call(a,function(x){return x.toUpperCase();});//['A','B','C']
The above is the detailed content of Discussion on creating and using array arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!