Home  >  Article  >  Web Front-end  >  Discussion on creating and using array arrays in JavaScript

Discussion on creating and using array arrays in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-18 11:40:321734browse

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

An array is a set of values ​​arranged in order. In essence, an array is a special object



typeof [1, 2, 3] // "object"

The special nature of an array is reflected in its keys A name is a set of integers (0, 1, 2...) arranged in order. Since the key names of array members are fixed, the array does not need to specify a key name for each element, but each member of the object must specify a key name


var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr));// ["0", "1", "2"]
var obj = {
name1: 'a',
name2: 'b',
name3: 'c'
};

The array is A special form of an object. Using square brackets to access array elements is just like using square brackets to access the properties of an object.


JavaScript language stipulates that the key names of objects are always strings, so the key names of arrays are actually Also a string. The reason why it can be read using numerical values ​​is that non-string key names will be converted to strings and then used as attribute names



o={}; //创建一个普通的对象
o[1]="one"; //用一个整数来索引它
//数值键名被自动转成字符串
var arr = ['a', 'b', 'c'];
arr['0'] // 'a'
arr[0] // 'a'

However, you must distinguish between array indexes and object attribute names: all indexes are attribute names, but only integer attribute names between 0~232-2 (4294967294) are indexes



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

Negative numbers or non-integers can be used to index arrays. But since it is not in the range of 0~2 to the power of 32 -2, it is only the attribute name of the array, not the index of the array. The obvious feature is that it does not change the length of the array



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

Each array has a length attribute, which is what makes it different from regular JavaScript object. For dense (that is, non-sparse) arrays, the length attribute value represents the number of elements in the array, and its value is 1 greater than the largest index in the array



[].length //=>0:数组没有元素
['a','b','c'].length //=>3:最大的索引为2,length为3

When the array is a sparse array, the length attribute value is greater than the number of elements. Similarly, its value is 1 greater than the largest index in the array.



[,,,].length; //3
(Array(10)).length;//10
var a = [1,2,3];
console.log(a.length);//3
delete a[1];
console.log(a.length);//3

The particularity is mainly reflected in the fact that the array length can be dynamically adjusted:


[1] If you assign a value to an array element and the index i is greater than or equal to the length of the existing array, the value of the length attribute will be set to i+1



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 = &#39;b&#39;;
for(var i in a){
console.log(a[i]);//1 2 &#39;b&#39;
} 
//跳过不是非负整数的i
var a = [1,,,2];
a.b = &#39;b&#39;;
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(&#39;a&#39;, &#39;b&#39;);
arrayLike[0] // &#39;a&#39;
arrayLike.length // 2
arrayLike instanceof Array // false

  【2】DOM方法(如document.getElementsByTagName()方法)返回的对象


// DOM元素
var elts = document.getElementsByTagName(&#39;h3&#39;);
elts.length // 3
elts instanceof Array // false

  【3】字符串


// 字符串
&#39;abc&#39;[1] // &#39;b&#39;
&#39;abc&#39;.length // 3
&#39;abc&#39; instanceof Array // false

  [注意]字符串是不可变值,故当把它们作为数组看待时,它们是只读的。如push()、sort()、reverse()、splice()等数组方法会修改数组,它们在字符串上是无效的,且会报错


var str = &#39;abc&#39;;
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 &#39;2&#39; of [object String]

  数组的slice方法将类数组对象变成真正的数组


var arr = Array.prototype.slice.call(arrayLike);

  javascript数组方法是特意定义为通用的,因此它们不仅应用在真正的数组而且在类数组对象上都能正确工作。在ECMAScript5中,所有的数组方法都是通用的。在ECMAScript3中,除了toString()和toLocaleString()以外的所有方法也是通用的


var a = {&#39;0&#39;:&#39;a&#39;,&#39;1&#39;:&#39;b&#39;,&#39;2&#39;:&#39;c&#39;,length:3};
Array.prototype.join.call(a,&#39;+&#39;);//&#39;a+b+c&#39;
Array.prototype.slice.call(a,0);//[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]
Array.prototype.map.call(a,function(x){return x.toUpperCase();});//[&#39;A&#39;,&#39;B&#39;,&#39;C&#39;]

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!

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