javascript type system Array object learning notes

  • 2020-11-26 18:40:44
  • OfStack

An array is an ordered list of values, and the object's property names are, in contrast, unordered. In essence, arrays use Numbers as lookup keys, and objects have user-defined property names. javascript does not have a true associative array, but objects can be used to implement associative functions

Array() is just one special type of Object(), that is, an instance of Array() is basically an instance of Object() with one extra function. Arrays can hold values of any type, which can be updated or deleted at any time, and arrays are dynamically resized

1. Array creation

As with most objects in Javascript, you can use the new operator along with the Array() constructor, or you can create array objects by using literal syntax

[1] Using the Array constructor (when using the Array constructor, the New operator can also be omitted), the values of an array instance can be passed to the constructor with comma-separated arguments, and the Array() constructor can accept 4294967295(approximately 4.3 billion) arguments

If there is only one argument: if the value is passed, it will be used to set the length of the array; If other types of arguments are passed, an array with only 1 item containing that value is created


var colors;
console.log(colors = new Array(),colors.length);//[] 0
console.log(colors = new Array('red','blue','green'),colors.length);//['red','blue','green'] 3
console.log(colors = new Array(20),colors.length);//[] 20
console.log(colors = new Array('red'),colors.length);//['red'] 1

var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100

[2] Array literal notation is used


var colors = ['red','blue','green'];
var colors = [];



//Array The constructor 
var myArray1 = new Array('blue','green','orange','red');
console.log(myArray1);//['blue','green','orange','red']
// Array literal representation 
var myArray2 = ['blue','green','orange','red'];
console.log(myArray2);//['blue','green','orange','red']



var colors = [1,2,]; 
// in IE8 And before that 1 a 3 A project , And each item is 1 , 2 and undefined The array. In other browsers is only contained 1 and 2 An array of 
var colors = [,,,];
 // in IE8 And will be created before 4 An array of items that would be created in other browsers 3 Item of the array  

2. Array operation

When reading and setting the values of an array, use square brackets and provide a zero-based numeric index of the corresponding value

The length of the array the length attribute represents the number of values in the array, and the numeric index of the array starts at 0. The length attribute is readable and writable, and by setting the Length attribute of the array, you can remove items from the end of the array or add new items to the array. If the length set is higher than the actual number of values in the array, the undefined value is added to the array; If you set the number of length values to less than the number of values in the array, the values in the array may be deleted


var myArray = ['blue','green','orange','red'];
console.log(myArray.length);//4
myArray.length = 99;
console.log(myArray.length);//99
myArray.length = 1;
console.log(myArray[1]);//undefined
console.log(myArray);//['blue']

 

var colors = ['red','blue','green'];
colors.length = 2;
alert(colors[2]);//undefined
colors.length = 4;
alert(colors[3]);//undefined

When a value is placed beyond the array size, the array recalculates its length value, which is equal to the index of the last item plus 1, and Javascript populates all indexes up to the current index with the undefined value


var myArray = [];
myArray[50] = 'blue';
console.log(myArray.length);//51
var colors = ['red','blue','green'];
colors[99] = 'black';
console.log(colors.length);//100  

[tips] Makes it easy to add new items to the end of an array using the length attribute

colors[colors.length] = 'black';

3. Inherited methods

toString()

Returns 1 comma-separated string concatenated from the string form of each value in the array

valueof()

It returns an array again


var colors = ['red','blue','green'];         
console.log(colors.valueOf());//['red','blue','green']
alert(colors.valueOf());//'red,blue,green' 
alert(colors.toString());//'red,blue,green'
alert(colors);//'red,blue,green'[ Pay attention to ] Due to the alert() To receive a string argument, it is called in the background toString() Method, you get alpha and beta toString() Method the same result 

toLocaleString()

When this method is called, the toLocaleString() method is called for every 1 item in the array


var person1 = {
  toLocaleString: function(){
    return 'Nikolaos';
  },
  toString: function(){
    return 'Nicholas';
  }
};
var person2 = {
  toLocaleString: function(){
    return 'Grigorios';
  },
  toString: function(){
    return 'Greg';
  }
};

var people = [person1,person2];
alert(people);//Nicholas,Greg
alert(people.toString());//Nicholas,Greg
alert(people.toLocaleString());//Nikolaos,Grigorios

4. Example method

An array of conversion
join()

Array inherited toLocaleString(), toString(), valueOf() methods, by default, return array entries as comma-separated characters; While the join() method can use different delimiters to build this string, the join() method takes just one argument, USES the string as a delimiter, and then returns a string containing all array entries. If no value is passed in to the join() method, or if undefined is passed in, use a comma as a delimiter


var colors = ['red','green','blue'];
console.log(colors.join(','));//'red,green,blue'
console.log(colors.join('||'));//'red||green||blue'
console.log(colors.join());//'red,green,blue'
console.log(colors.join(undefined));//'red,green,blue'[ Pay attention to ]IE7- Will use undefined As a separator 

[Note] If an item in the array has a value of null or undefined, the value is represented as an empty string in the result returned by the join(), toLocaleString(), toString(), and valueOf() methods

Array detection
Since ES3 made this provision, the classic problem of determining whether an object is an array has arisen. A common approach of 1 is to use the instance operator, but this approach has its limitations; ES5 specifically added the isArray() method to detect arrays


var value = [123];
console.log(value instanceof Array);//true

The problem with the instanceof operator is that it assumes only one global execution environment, and if the web page contains multiple frameworks, there are actually two or more different global environments, and thus two or more different versions of the Array constructor. If you pass an array from one frame to another, the array that is passed in has a different constructor than the array that was created natively in the second frame


 // Cannot be Shared in different frameworks prototype attribute 
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var value = new window.frames[0].Array;
console.log(value instanceof Array);//false
console.log(value.constructor == Array);//false

However, the toString() method can be called across the prototype chain in different frameworks


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
0

ES5 added the Array.isArray () method to determine whether a value is an array or not, regardless of which global environment it was created in

Array.isArray()


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
1

The stack and queue
push()

You can take any number of arguments, add them to the end of the array one by one, and return the modified length of the array

pop()

Removes the last item from the end of the array, reduces the length value of the array, and returns the removed item

shift()

Removes the first item in the array and returns it, while the length of the array is reduced by 1(shift() and push() can be used in combination to simulate queues)

unshift()

Add any item to the front of the array and return the new array length (using unshift() and pop() to simulate the queue from the opposite direction)

[Note]IE7- The browser unshift() method always returns undefined


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
2

Sorting method
reverse()

Reverses the order of the array, returning the sorted array; The original array order has also changed


var array = [1,2,4,3,5];
console.log(array,array.reverse());//[5,3,4,2,1] [5,3,4,2,1]
var array = ['str',true,3];
console.log(array,array.reverse());//[3,true,'str'] [3,true,'str']

sort()

By default, array items are sorted in ascending string order, and the sort method calls the toString() method for each array item, and then compares the resulting string order, returning the sorted array with the original array order changed


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
4

[Note] The sort() method can take a comparison function as an argument to specify which value precedes which. The comparison function takes two arguments, returns a negative number if the first argument should be before the second argument, returns 0 if the two arguments are equal, and returns a positive number if the first argument should be after the second argument

[tips] comparison function


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
5

For numeric types or valueOf() methods that return object types of numeric types, the comparison function can be simplified to:


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
6

[tips] creates 1 random number group


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
7

Operation method
concat()

Create 1 new array based on all items in the current array, create 1 copy of the current array, add the parameters received to the end of this copy, and return the newly built array (concat() does not affect the original array)

If you don't pass arguments to the concat() method, it simply copies the current array; If the argument is one or more arrays, the method adds each item from those arrays to the result array. If the values passed are not arrays, they are simply added to the end of the result array


var numbers = [1,2];
console.log(numbers,numbers.concat());//[1,2] [1,2]
console.log(numbers,numbers.concat([5,4,3],[3,4,5],1,2));//[1,2] [1,2,5,4,3,3,4,5,1,2]

slice()

Creates a new array based on one or more items in the current array, takes one or two arguments to return the starting and ending positions of the items, and finally returns a new array (slice() does not affect the original array)

If there are no arguments, the original array is returned; If there is only one argument, the slice() method returns all entries from the specified position of that argument to the end of the current array; If there are two arguments, the method returns the item between the start and end positions, but not the end position; If the parameter is a negative number, the array length plus a negative number is used as the parameter. Returns an empty array if the end position is smaller than the start position


var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
9

splice()

The original array becomes the modified array, and splice() returns an array of deleted items from the original array, or an empty array if there are no deleted items. If the first parameter is a negative number, the array length plus a negative number is used as the parameter. If the second argument is negative, 0 is used as the argument

[1] Delete: Two parameters are the location of the first item to be deleted and the number of items to be deleted

[2] Insert: Three parameters are the starting position, 0(the cardinality to be deleted), and the item to be inserted

[3] Substitution: Three parameters are the starting position, the number of items to be deleted, and the items to be inserted


 var numbers = [1,2,3,4,5];
console.log(numbers.splice(),numbers);//[] [1, 2, 3, 4, 5]
console.log(numbers.splice(0,2),numbers);//[1,2] [3,4,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(1,0,11,12),numbers);//[] [1,11,12,2,3,4,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(1,3,11,12),numbers);//[2,3,4] [1,11,12,5] 
var numbers = [1,2,3,4,5];
console.log(numbers.splice(-4,3,11,12),numbers);//-4+5=1 -> [2,3,4] [1,11,12,5] 
var numbers = [1,2,3,4,5];
console.log(numbers.splice(-4,-3,11,12),numbers);//-4+5=1 -> [] [1,11,12,2,3,4,5]

Location method
ES5 adds two position methods, indexOf() and lastIndexOf(), to an array instance. Both methods take two parameters: the item to look for, and the index (optional) that represents the starting point of the lookup. Returns the position of the first lookup item in the array, or -1 if it is not found (the location method does not affect the original array)

The [note] method USES the congruent operator when comparing parameters

indexOf() looks backwards from front
lastIndexOf() looks from back to front


var numbers = [1,2,3,4,5,4,3,2,1];
console.log(numbers.indexOf(4));//3
console.log(numbers.lastIndexOf(4));//5
console.log(numbers.indexOf(4,4));//5
console.log(numbers.lastIndexOf(4,4));//3

 

var person = {name: 'Nicholas'};
var people = [{name: 'Nicholas'}];
var morePeople = [person];
alert(people.indexOf(person));//-1, because person and people[0] Although the values are the same, they are two references 
alert(morePeople.indexOf(person));//0 Because the person and morepeople[0] Is the same 1 A reference 
alert(morePeople.indexOf({name: 'Nicholas'}));//-1, Because it's not the same 1 A reference 

[tips] returns all index values for items that meet the criteria


function allIndexOf(array,value){
  var result = [];
  var pos = array.indexOf(value);
  if(pos === -1){
    return -1;
  }
  while(pos > -1){
    result.push(pos);
    pos = array.indexOf(value,pos+1);
  }
  return result;
}
var array = [1,2,3,3,2,1];
console.log(allIndexOf(array,1));//[0,5]

Above is the detailed content of this article, I hope to help you learn javascript programming.


Related articles: