Data type - array

Table of contents

5. Array

1.Definition

2. The nature of arrays

3.length attribute

4.in operator

5.for...in loop and array traversal

6. Gap in array

7. Array-like objects


5. Array

1.Definition

An array is a set of values ​​arranged in order. The position of each value is numbered (starting from 0), and the entire array is represented by square brackets.

2. The nature of arrays

Essentially, arrays are a special kind of objects. The typeof operator will return an array of type object.

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

//上面代码表明,typeof运算符认为数组的类型就是对象。

The particularity of an array is that its keys are a set of integers (0, 1, 2...) arranged in order.

var arr = ['a', 'b', 'c'];

Object.keys(arr)
// ["0", "1", "2"]

//上面代码中,Object.keys方法返回数组的所有键名。可以看到数组的键名就是整数0、1、2。

 

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

var arr = ['a', 'b', 'c'];

arr['0'] // 'a'
arr[0] // 'a'

//上面代码分别用数值和字符串作为键名,结果都能读取数组。原因是数值键名被自动转为了字符串。


//这点在赋值时也成立。一个值总是先转成字符串,再作为键名进行赋值。

var a = [];

a[1.00] = 6;
a[1] // 6

The object has two methods for reading members: dot structure (object.key) and square bracket structure (object[key]). However, dot structures cannot be used for numeric key names.

var arr = [1, 2, 3];
arr.0 // SyntaxError
/*上面代码中,arr.0的写法不合法,因为单独的数值不能作为标识符(identifier)。所以,数组成员只能
用方括号arr[0]表示(方括号是运算符,可以接受数值)。*/

3.length attribute

Arraylength attribute returns the number of members of the array.

JavaScript uses a 32-bit integer to save the number of elements in the array. This means that the maximum number of array members is 4294967295 (232 - 1), which means that the maximum value of the length attribute is 4294967295.

As long as it is an array, it must havelength attributes. This attribute is a dynamic value equal to the largest integer in the key name plus 1.

The numeric keys of the array do not need to be consecutive.lengthThe value of the attribute is always greater than the largest integer key1. In addition, this also shows that the array is a dynamic data structure, and the members of the array can be added or removed at any time.

lengthThe attribute is writable. If you manually set a value smaller than the current number of members, the number of members in the array will automatically be reduced to the value set by length.

var arr = [ 'a', 'b', 'c' ];
arr.length // 3

arr.length = 2;
arr // ["a", "b"]

An effective way to clear the array is to set the length attribute to 0. If the artificial settinglength is greater than the current number of elements, the number of members of the array will be increased to this value, and the new positions will be empty

If is manually setlength to an illegal value, JavaScript will report an error.

// 设置负值
[].length = -1
// RangeError: Invalid array length

// 数组元素个数大于等于2的32次方
[].length = Math.pow(2, 32)
// RangeError: Invalid array length

// 设置字符串
[].length = 'abc'
// RangeError: Invalid array length

Set the keys of the array to strings and decimals respectively. The result will not affect thelength attribute. Because the value of the length attribute is equal to the largest numeric key plus 1, and this array does not have an integer key, the length attribute remains as 0.

If the key name of the array is to add a value out of the range, the key name will be automatically converted to a string.

var arr = [];
arr[-1] = 'a';
arr[Math.pow(2, 32)] = 'b';

arr.length // 0
arr[-1] // "a"
arr[4294967296] // "b"
/*上面代码中,我们为数组arr添加了两个不合法的数字键,结果length属性没有发生变化。这些数字键都变
成了字符串键名。最后两行之所以会取到值,是因为取键值时,数字键名会默认转为字符串。*/

4.in operator

Operator that checks whether a certain key name existsin, applicable to objects as well as arrays.

var arr = [ 'a', 'b', 'c' ];
2 in arr  // true
'2' in arr // true
4 in arr // false

//上面代码表明,数组存在键名为2的键。由于键名都是字符串,所以数值2会自动转成字符串。

If a position in the array is empty, the in operator returnsfalse.

var arr = [];
arr[100] = 'a';

100 in arr // true
1 in arr // false

//上面代码中,数组arr只有一个成员arr[100],其他位置的键名都会返回false。

5.for...in loop and array traversal

for...inLoops can not only traverse objects, but also arrays. After all, arrays are just a special kind of object.

var a = [1, 2, 3];

for (var i in a) {
  console.log(a[i]);
}
// 1
// 2
// 3

for...inNot only will all numeric keys in the array be traversed, but non-numeric keys will also be traversed.

var a = [1, 2, 3];
a.foo = true;

for (var key in a) {
  console.log(key);
}
// 0
// 1
// 2
// foo

To traverse the array, consider using the for loop or while loop.

var a = [1, 2, 3];

// for循环
for(var i = 0; i < a.length; i++) {
  console.log(a[i]);
}

// while循环
var i = 0;
while (i < a.length) {
  console.log(a[i]);
  i++;
}

var l = a.length;
while (l--) {
  console.log(a[l]);
}

The arrayforEach method can also be used to traverse the array. For details, see the Array Object chapter of the "Standard Library".

var colors = ['red', 'green', 'blue'];
colors.forEach(function (color) {
  console.log(color);
});
// red
// green
// blue

6. Gap in array

When there is an empty element at a certain position in the array, that is, there is no value between the two commas, we say that the array has a hole.

var a = [1, , 1];
a.length // 3

/*需要注意的是,如果最后一个元素后面有逗号,并不会产生空位。也就是说,有没有这个逗号,结果都是一
样的。*/

var a = [1, 2, 3,];

a.length // 3
a // [1, 2, 3]

//数组最后一个成员后面有一个逗号,这不影响length属性的值,与没有这个逗号时效果一样。

The empty bits of the array can be read, and returnundefined.

Using thedelete command to delete an array member will create a gap and will not affect thelength attribute.

There is a difference between a certain position in the array being empty and a certain position being undefined. If it is empty, use the forEach method, for...in structure, and Object.keys method of the array. During traversal, empty positions will be skipped. That is to say, the empty position means that the array does not have this element, so it will not be traversed, and undefined means that the array has this element, and the value is undefined, so it will not be traversed. will be skipped.

7. Array-like objects

If all the keys of an object are positive integers or zero, and it has length attributes, then the object is like an array, and is syntactically called an "array-like object" ( array-like object).

Array-like objects are not arrays because they do not have array-specific methods.

The fundamental characteristic of "array-like object" is that it haslength attributes. This kind oflength attributes are not dynamic values ​​and will not change with the members. And change.

Typical "array-like objects" are functionarguments objects, most sets of DOM elements, and strings.

// arguments对象
function args() { return arguments }
var arrayLike = args('a', 'b');

arrayLike[0] // 'a'
arrayLike.length // 2
arrayLike instanceof Array // false

// DOM元素集
var elts = document.getElementsByTagName('h3');
elts.length // 3
elts instanceof Array // false

// 字符串
'abc'[1] // 'b'
'abc'.length // 3
'abc' instanceof Array // false

The arrayslice method can turn an "array-like object" into a real array.

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

/*除了转为真正的数组,“类似数组的对象”还有一个办法可以使用数组的方法,就是通过call()把数组的方法
放到对象上面。*/

function print(value, index) {
  console.log(index + ' : ' + value);
}

Array.prototype.forEach.call(arrayLike, print);

/*上面代码中,arrayLike代表一个类似数组的对象,本来是不可以使用数组的forEach()方法的,但是通过call(),可以把forEach()嫁接到arrayLike上面调用。*/


//下面的例子就是通过这种方法,在arguments对象上面调用forEach方法。

// forEach 方法
function logArgs() {
  Array.prototype.forEach.call(arguments, function (elem, i) {
    console.log(i + '. ' + elem);
  });
}

/*注意,这种方法比直接使用数组原生的forEach要慢,所以最好还是先将“类似数组的对象”转为真正的数组,然后再直接调用数组的forEach方法。*/

var arr = Array.prototype.slice.call('abc');
arr.forEach(function (chr) {
  console.log(chr);
});
// a
// b
// c

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/lxlsygxs2017/article/details/113765848