array of javascript

Posted by bigfatpig on Mon, 15 Jul 2019 19:52:00 +0200

Create arrays

Use literal grammar and Array() constructors.

Literal

Using array literals is the easiest way to create arrays. You can use all the elements in square brackets to separate them.

var s = [];//Empty array
var s = [1,1,1,1,1]//An array with five values.

Although javascript arrays are ordered lists of data in other languages, unlike other languages, each of js can retain any type of data.

var s = [1,true,'a'];

Array literals are not necessarily constants, they can be arbitrary expressions.

var base = 1024;
var table = [base,base+1,base+2,base+3];

It can contain object literals or other array literals.

var s = [[1,{a:2,y:3}],[2,{w:8,r:7}]];

If the elements of an array are still arrays, they are multidimensional arrays.

var s = [[1, 2], [3, 4]];

When using numeric literal representation, the Array constructor is not called.

Function Construction

There are three ways to call constructors

1: No parameters, create an empty array.

//This method is used to create an empty array, equivalent to [];
var s = new Array();

2: There is a parameter that specifies the length of the array.

var s = new Array(10);
console.log(s);//[];
console.log(a[0],a.length);//undefined 10

3: If there is a parameter of another type, an array containing only one item of that value is created.

var s = new Array('10');
console.log(s);//['10']
console.log(s.length);//1

4: When there are multiple parameters, the parameters represent specific array elements.

var a = new Array(1,2,3);
console.log(a);//[1,2,3]
console.log(a[0],a[1],a[2]);//1 2 3

5: new operation symbols can be omitted when using the Array constructor.

var a1 = Array();
var a2 = Array(10);
var a3 = Array(1,2,3);
console.log(a1,a2,a3);//[] [] [1,2,3]

Array essence

Arrays are a set of values arranged in order, and in essence, arrays are a special kind of object.

typeof [1,2,4];// object;

The particularity of an array is that its key name is a set of integers (0, 1, 2, 3) arranged in order; because the key name of the members of the array is fixed, the key name of each element should not be specified for the number of times. Each member of the object must specify a key name.

var s = [1,2,3,5];
console.log(Object.key(s));// ["0", "1", "2"];

var obj = {
    name1: 'a',
    name2: 'b',
    name3: 'c'
};

Arrays are a special form of objects, using square brackets to access array elements, just like square brackets to access the attributes of objects.

js language stipulates that the key name of an object is always a string, so the key name of an array is actually a string, all of which can be read by an array, because the key name of a non-string will be converted to a string, and then used as an attribute name.

o={};       //Create a common object
o[1]="one"; //Index it with an integer

//The numeric key name is automatically converted to a string
var arr = ['a', 'b', 'c'];
arr['0'] // 'a'
arr[0] // 'a'

However, it is important to distinguish between array indexes and object attribute names: all indexes are attribute names, but only integer attribute names between 0~2 (32 power) - 2 (4294967294) are indexed.
  

var a = [];

//Indexes
a['1000'] = 'abc';
a[1000] // 'abc'

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

Individual indexes cannot be represented, so array elements can only be represented in square brackets.

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

Negative and non-integer numbers can be used to index arrays, because they are not in the range of 32-2 from 0 to 2, so they are only the attribute names of arrays. Instead of the index of the array, the obvious feature is that it does not change the length of the array.

//Property name
a[-1.23]=true;
console.log(a.length);//3

//Indexes
a[10] = 5;
console.log(a.length);//11

//Property name
a['abc']='testing';
console.log(a.length);//11

* Sparse array*

Sparse arrays are arrays that contain discontinuous indexes starting at 0.

The most direct way to know sparse arrays is to use the delete operator.

var a = [1,2,3,4,5];
delete a[1];//Delete an element indexed as one.
console.log(a[1]);//undefined
console.log(1 in a);//false

Element values can be omitted between commas of arrays, and sparse arrays can be known by omitting element values.

var a =[1,,3,4,5];
console.log(a[1]);//undefined
console.log(1 in a);//false

If commas are used at the end of the array, there is a difference between browsers. Standard browsers ignore the comma, while IE8 will undefined at the end of the field.

//Standard browser output[1,2],and IE8-Browser Output[1,2,undefined]
var a = [1,2,];
console.log(a);

//Standard browser output2,and IE8-Browser Output3
var a = [,,];
console.log(a.length);

Sufficiently sparse arrays are usually implemented more slowly than dense arrays and have higher memory utilization. In such arrays, the time to find elements is as long as that of conventional object attributes.

Array length

Each array has a length attribute, which distinguishes it from a regular javascript object. For dense (i.e., non-sparse) arrays, the length attribute value represents the number of elements in the array, and its value is 1 larger than the largest index in the array.

[].length     //=> 0: Arrays have no elements
['a','b','c'].length   //=> 3: Maximum index is 2, length is 3

When an array is a sparse array, the length attribute value is greater than the number of elements. Similarly, the value is greater than 1 of 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 of arrays is that the length of arrays can be dynamically adjusted.

  1. If an array element is assigned a value whose index I is greater than or equal to the length of an existing array, the value of the length attribute is 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
  1. When the length attribute is set to a non-negative integer n of less than the current length, elements whose index value of the current array is greater than or equal to n will be deleted from it.
a=[1,2,3,4,5];   //Start with an array of five elements
a.length = 3;    //Now a is [1, 2, 3]
a.length = 0;    //Delete all elements. a is [].
a.length = 5;    //The length is 5, but there are no elements, like new Array(5)

An effective way to empty the array is to set the length attribute to 0.

  1. Set the length attribute value of the array to be greater than its current length. Actually, this doesn't add new elements to the array, it just creates an empty area at the end of the array.
var a = ['a'];
a.length = 3;
console.log(a[1]);//undefined
console.log(1 in a);//false

If length is artificially set to an illegal value (i.e. a value outside the range of 0-232-2), javascript will report an error.

// Set negative values
[].length = -1// RangeError: Invalid array length

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

// Setting Strings
[].length = 'abc'// RangeError: Invalid array length

Because arrays are essentially objects, attributes can be added to arrays, but this does not affect the value of the length attribute.
 

var a = [];

a['p'] = 'abc';
console.log(a.length);// 0

a[2.1] = 'abc';
console.log(a.length);// 0

Array traversal

Traversing array elements using for loops is the most common method

var a = [1, 2, 3];
for(var i = 0; i < a.length; i++) {
  console.log(a[i]);
}

You can also use the while loop

var a = [1, 2, 3];
var l = a.length;
while(l--) {
    console.log(a[i]);
}

If the array is sparse, you need to add some additional conditions to use the for loop

//Skip non-existent elements
var s = [1,,,6];
for(var i=0;i<s.length;i++){
    if(!(i in a)){
        continue
    }else{
        console.log(a[i])
    }
}

Use the for/in loop to process sparse arrays. Each time, an enumerable attribute name (including an array index) is paid to the loop variable. Non-existent indexes will not be traversed

var s = [1,,,2];
for(var i in s){
    console.log(s[i]);
}

Because the for / in loop can enumerate inherited attribute names, such as methods added to Array.prototype. For this reason, for/in loops should not be used on arrays unless additional detection methods are used to filter unwanted attributes.

var a = [1,,,2];
a.b = 'b';
for(var i in a){
    console.log(a[i]);//1 2 'b'
}
//Skipping i that is not a nonnegative integer
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
}

The javascript specification allows for / in loops to traverse the properties of objects in different order. Often, the traversal implementation of array elements is ascending, but it is not guaranteed to be so. In particular, if an array has both object attributes and array elements, the returned attribute names are likely to be in the order of creation rather than the order of value size. If the algorithm depends on the order of traversal, it's better not to use for/in but to use a regular for loop.

Class array

Objects with length attributes and corresponding non-negative integer attributes are called array-like objects.

var s = {};
var i = 0;
while (i < 10){
    s[i] = i*i;
    i++;
}
s.length = i;


var total = 0;
for(var j = 0; j < a.length; j++){
    total += a[j];
}

There are three common class array objects:

1: arguments object

// arguments object
function args() { return arguments }
var arrayLike = args('a', 'b');
arrayLike[0] // 'a'
arrayLike.length // 2
arrayLike instanceof Array // false

Objects returned by DOM methods, such as document.getElementsByTagName() methods

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

Character string

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

Strings are immutable, so when they are treated as arrays, they are read-only. Array methods such as push(), sort(), reverse(), splice() modify arrays, which are invalid on strings and can cause errors.

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]

The slice method of arrays turns class array objects into real arrays

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

javascript array methods are specifically defined as generic, so they work correctly not only on real arrays but also on class array objects. In ECMAScript 5, all array methods are generic. In ECMAScript3, all methods except toString() and toLocaleString() are also common.
 

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 feeling is sublimated.

Topics: Attribute Javascript less ECMAScript