The basic data type of javascript learning, array

array

definition

An array is a sequenced set of values. Each value position is numbered (starting at 0), and the entire array is denoted by square brackets.

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

aThe , b, in the above code cform an array, and the square brackets at both ends are the signs of the array. aIt's position 0, bit's position 1, cit's position 2.

In addition to assigning values ​​at definition time, arrays can also be defined first and assigned later.

var scar = [];
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';

Any type of data can be put into an array.

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

arrThe three members of the above array are objects, arrays, and functions in turn.

If the elements of the array are also arrays, a multidimensional array is formed.

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

The nature of arrays

Essentially, arrays are a special kind of object. typeofThe operator returns the type of the array is object.

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

The above code shows that typeofthe operator considers the type of the array to be an object.

The particularity of the array is reflected in that its key name is a set of integers (0, 1, 2...) arranged in order.

var arr = ['a', 'b', 'c'];
Object.keys(arr)
// ["0", "1", "2"]

In the above code, Object.keysthe method returns all the key names of the array. You can see that the keys of the array are integers 0, 1, and 2.

Since the key names of array members are fixed (always 0, 1, 2... by default), arrays do not need to specify a key name for each element, but each member of an object must specify a key name. The JavaScript language stipulates that the key names of objects are all strings, so the key names of arrays are actually strings. The reason why it can be read as a value is that the key name that is not a string will be converted to a string.

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

The above code uses numeric values ​​and strings as keys respectively, and the results can read arrays. The reason is that the numeric key names are automatically converted to strings.

Note that this also holds for assignment. A value is always converted to a string first, and then assigned as a key.

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

In the above code, since 1.00it is converted into a string , the value can be read 1through the numeric key .1

As mentioned in the previous chapter, objects have two ways to read members: the dot structure ( object.key) and the bracket structure ( object[key]). However, for numeric keys, the dot structure cannot be used.

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

In the above code, arr.0the writing method of is illegal because a single value cannot be used as an identifier. Therefore, array members can only be represented by square brackets arr[0](square brackets are operators and can accept values).

length property

An array lengthproperty that returns the number of members of the array.

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

JavaScript uses a 32-bit integer to store the number of elements in an array. This means that there are at most 4294967295 (232 - 1) array members, which means that lengththe maximum value of an attribute is 4294967295.

As long as it is an array, it must have lengthattributes. This attribute is a dynamic value equal to the largest integer in the key name plus 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

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

lengthAttributes are writable. If you manually set a value smaller than the current number of members, the number of members of the array will be automatically reduced to the lengthset value.

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

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

The above code indicates that when lengththe attribute of the array is set to 2 (that is, the largest integer key can only be 1), then the integer key 2 (value c) is no longer in the array and is automatically deleted.

An effective way to clear an array is to lengthset the property to 0.

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

arr.length = 0;
arr // []

If the artificial setting lengthis greater than the current number of elements, the number of members of the array will increase to this value, and the newly added positions are all vacancies.

var a = ['a'];

a.length = 3;
a[1] // undefined

The above code indicates that when lengththe attribute is set to be greater than the number of arrays, the newly added position will be returned undefined.

If artificially set lengthto an illegal value, JavaScript will report an error.

// set negative value
[].length = -1
// RangeError: Invalid array length

// The number of array elements is greater than or equal to 2 to the 32nd power
[].length = Math.pow(2, 32)
// RangeError: Invalid array length

// set the string
[].length = 'abc'
// RangeError: Invalid array length

It is worth noting that since arrays are essentially objects, properties can be added to arrays, but this does not affect lengththe value of the properties.

var a = [];

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

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

The above code sets the keys of the array to strings and decimals respectively, and the result does not affect lengththe properties. Because lengththe value of the attribute is equal to the largest numeric key plus 1, and this array has no integer keys, so lengththe attribute remains as 0.

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

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

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

In the above code, we arradded two illegal numeric keys to the array, and the resulting lengthproperties did not change. These numeric keys are all turned into string key names. The reason why the last two lines get the value is because when getting the key value, the numeric key name will be converted to a string by default.

in operator

An operator that checks whether a key exists in, works on objects as well as arrays.

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

The above code shows that the array has a key named 2key. Since the key names are all strings, the values 2​​will be automatically converted to strings.

inNote that the operator returns if a position in the array is empty false.

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

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

In the above code, the array arrhas only one member arr[100], and the key names in other positions will be returned false.

for...in loops and array traversal

for...inLoops can not only traverse objects, but also traverse 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

However, for...innot only will all the numeric keys of 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

When the above code traverses the array, it also traverses non-integer keys foo. Therefore, iterating for...inover arrays is not recommended.

The traversal of the array can consider using forloops or whileloops.

var a = [1, 2, 3];

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

// while loop
where i = 0;
while (i < a.length) {
  console.log(a[i]);
  i++;
}

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

The above code is written in three ways to traverse the array. The last way of writing is reverse traversal, that is, traversing from the last element to the first element.

The method of array forEachcan also be used to traverse the array, see the chapter of Array object in "Standard Library" for details.

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

slots in the array

When a certain position of the array is an empty element, that is, there is no value between two commas, we call the array a hole.

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

The above code shows that the empty space of the array does not affect lengththe property. Although this position has no value, the engine still considers this position to be valid.

It should be noted that if there is a comma after the last element, no space will be created. In other words, with or without this comma, the result is the same.

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

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

In the above code, there is a comma after the last member of the array, which does not affect lengththe value of the attribute, which is the same as without this comma.

The empty slots of the array can be read and returned undefined.

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

Using deletethe command to delete an array member will form a vacancy and will not affect lengththe attribute.

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

a[1] // undefined
a.length // 3

The above code deletes the second element of the array with deletethe command, and this position forms a vacancy, but it lengthhas no effect on the attribute. That is, lengththe attribute does not filter for slots. Therefore, lengthyou must be very careful when using attributes for array traversal.

undefinedA certain position of the array is empty, which is different from a certain position . If it is a vacancy, use forEachthe method, for...instructure, and Object.keysmethod of the array to traverse, and the vacancy will be skipped.

var a = [, , ,];

a.forEach(function (x, i) {
  console.log(i + '. ' + x);
})
// do not produce any output

for (var i in a) {
  console.log(i);
}
// do not produce any output

Object.keys(a)
// []

If a certain position is undefined, it will not be skipped when traversing.

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']

That is to say, the vacancy means that the array does not have this element, so it will not be traversed, but undefinedit means that the array has this element, and the value is undefined, so the traversal will not be skipped.

array-like object

If all the keys of an object are positive integers or zero, and have lengthproperties, then the object is like an array, syntactically called an "array-like object".

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

obj[0] // 'a'
obj[1] // 'b'
obj.length // 3
obj.push('d') // TypeError: obj.push is not a function

In the code above, the object objis an array-like object. However, "array-like objects" are not arrays, because they do not have methods specific to arrays. The object objdoes not have an array pushmethod, and an error will be reported when using this method.

The fundamental characteristic of an "array-like object" is that it has lengthproperties. As long as it has lengthproperties, this object can be considered similar to an array. But there is a problem, this lengthattribute is not a dynamic value, it will not change as the member changes.

var obj = {
  length: 0
};
obj[3] = 'd';
obj.length // 0

The code above objadds a numeric key to the object, but lengththe properties don't change. That means objit's not an array.

Typical "array-like objects" are argumentsobjects of functions, as well as most DOM element sets, and strings.

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

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

// set of DOM elements
var elts = document.getItemsByTagName('h3');
elts.length // 3
each instanceof Array // false

// string
'abc'[1] // 'b'
'abc'.length // 3
'abc' instanceof Array // false

The above code contains three examples, none of them are arrays ( instanceofthe operator returns false), but they all look very much like arrays.

Array slicemethods can turn "array-like objects" into real arrays.

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

In addition to converting to a real array, there is another way for "array-like objects" to use array methods, which is by call()putting array methods on objects.

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

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

In the above code, it represents an array-like object. Originally, the array method arrayLikecannot be used , but it can be grafted to the above call.forEach()call()forEach()arrayLike

The following example uses this method argumentsto call a method on an object forEach.

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

// equivalent to for loop
function logArgs() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(i + '. ' + arguments[i]);
  }
}

Strings are also array-like objects, so Array.prototype.forEach.calltraversal can also be used.

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

forEachNote that this method is slower than using the original array directly , so it is better to convert the "array-like object" into a real array first, and then directly call forEachthe method of the array.

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

reference link

Guess you like

Origin blog.csdn.net/zy_dreamer/article/details/132159238