# 数组

## 定义 #

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

``````var arr = [];

arr = 'a';
arr = 'b';
arr = 'c';
``````

``````var arr = [
{a: 1},
[1, 2, 3],
function() {return true;}
];

arr // Object {a: 1}
arr // [1, 2, 3]
arr // function (){return true;}
``````

``````var a = [[1, 2], [3, 4]];
a // 2
a // 4
``````

## 数组的本质 #

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

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

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

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

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

``````var a = [];

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

``````var arr = [1, 2, 3];
arr.0 // SyntaxError
``````

## length 属性 #

``````['a', 'b', 'c'].length // 3
``````

JavaScript 使用一个32位整数，保存数组的元素个数。这意味着，数组成员最多只有 4294967295 个（232 - 1）个，也就是说`length`属性的最大值就是 4294967295。

``````var arr = ['a', 'b'];
arr.length // 2

arr = 'c';
arr.length // 3

arr = 'd';
arr.length // 10

arr = 'e';
arr.length // 1001
``````

`length`属性是可写的。如果人为设置一个小于当前成员个数的值，该数组的成员数量会自动减少到`length`设置的值。

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

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

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

arr.length = 0;
arr // []
``````

``````var a = ['a'];

a.length = 3;
a // undefined
``````

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

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

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

``````var a = [];

a['p'] = 'abc';
a.length // 0

a[2.1] = 'abc';
a.length // 0
``````

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

arr.length // 0
arr[-1] // "a"
arr // "b"
``````

## in 运算符 #

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

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

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

## for...in 循环和数组的遍历 #

`for...in`循环不仅可以遍历对象，也可以遍历数组，毕竟数组只是一种特殊对象。

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

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

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

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

``````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]);
}
``````

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

## 数组的空位 #

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

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

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

``````var a = [, , ,];
a // undefined
``````

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

a // undefined
a.length // 3
``````

``````var a = [, , ,];

a.forEach(function (x, i) {
console.log(i + '. ' + x);
})
// 不产生任何输出

for (var i in a) {
console.log(i);
}
// 不产生任何输出

Object.keys(a)
// []
``````

``````var a = [undefined, undefined, undefined];

a.forEach(function (x, i) {
console.log(i + '. ' + x);
});
// 0. undefined
// 1. undefined
// 2. undefined

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

Object.keys(a)
// ['0', '1', '2']
``````

## 类似数组的对象 #

``````var obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};

obj // 'a'
obj // 'b'
obj.length // 3
obj.push('d') // TypeError: obj.push is not a function
``````

“类似数组的对象”的根本特征，就是具有`length`属性。只要有`length`属性，就可以认为这个对象类似于数组。但是有一个问题，这种`length`属性不是动态值，不会随着成员的变化而变化。

``````var obj = {
length: 0
};
obj = 'd';
obj.length // 0
``````

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

arrayLike // 'a'
arrayLike.length // 2
arrayLike instanceof Array // false

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

// 字符串
'abc' // 'b'
'abc'.length // 3
'abc' instanceof Array // false
``````

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

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

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

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

// 等同于 for 循环
function logArgs() {
for (var i = 0; i < arguments.length; i++) {
console.log(i + '. ' + arguments[i]);
}
}
``````

``````Array.prototype.forEach.call('abc', function (chr) {
console.log(chr);
});
// a
// b
// c
``````

``````var arr = Array.prototype.slice.call('abc');
arr.forEach(function (chr) {
console.log(chr);
});
// a
// b
// c
``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.7058743,"math_prob":0.9956016,"size":7247,"snap":"2020-24-2020-29","text_gpt3_token_len":3978,"char_repetition_ratio":0.15573658,"word_repetition_ratio":0.09848485,"special_character_ratio":0.34800607,"punctuation_ratio":0.21076573,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99375784,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-06-04T15:04:16Z\",\"WARC-Record-ID\":\"<urn:uuid:0a63b3f9-17eb-499b-8c0a-5ad49c23981a>\",\"Content-Length\":\"59076\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:959739f6-843e-4de6-9ecc-3be81934c5a4>\",\"WARC-Concurrent-To\":\"<urn:uuid:0ad42cff-b21d-4889-b906-830a736331d4>\",\"WARC-IP-Address\":\"104.18.32.244\",\"WARC-Target-URI\":\"https://wangdoc.com/javascript/types/array.html\",\"WARC-Payload-Digest\":\"sha1:UARPGT2OMRCPFRR7SAD7MZQ7WPD7FNKY\",\"WARC-Block-Digest\":\"sha1:5ZNTLUI76DN7YRACCMLNCMYQKVBHDY3Y\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-24/CC-MAIN-2020-24_segments_1590347441088.63_warc_CC-MAIN-20200604125947-20200604155947-00361.warc.gz\"}"}