Js-w3school (2020.2.3) [js array]

Keywords: Javascript Attribute Fragment

1.JavaScript arrays are used to store multiple values in a single variable.
2. Create array:
Array text method:

var cars = ["Saab", "Volvo", "BMW"];

Or use the keyword new

var cars = new Array("Saab", "Volvo", "BMW");

3. We refer to an array element by referring to index number (subscript)
4. Through JavaScript, you can access the complete array by referencing the array name
5. Array is a special type of object. Using typeof operators on arrays in JavaScript returns "object"
6. The length property returns the length of the array (the number of array elements). The length property is always greater than the highest array index (subscript).

var last = fruits[fruits.length - 1];// Access the last element
var first = fruits[0];//Access the first element

7. The safest way to traverse an array is to use a "for" loop.
You can also use the Array.foreach() function

var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
  text += "<li>" + value + "</li>";
}

8. The best way to add new elements to an array is to use the push() method

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");                // Add a new element (Lemon) to fruits

You can also use the length attribute to add new elements to the array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon";     // Add a new element (Lemon) to fruits

9. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes.

var person = [];
person["firstName"] = "Bill";
person["lastName"] = "Gates";
person["age"] = 62;
var x = person.length;         // person.length will return 0
var y = person[0];              // person[0] will return undefined

In JavaScript, arrays use numeric indexes.
In JavaScript, objects use named indexes.
10. Avoid new Array()
There is no need to use JavaScript's built-in array constructor, new Array()

var points = new Array();         // difference
var points = [];                  // excellent

For example, the following will cause ambiguity: whether an array has 40 elements or whether we want an array with only one element whose value is 40

var points = new Array(40);       // Create an array of 40 undefined elements!!!
  1. How to recognize arrays
    Array.isArray(fruits); / / returns true
    Custom isArray functions:
function isArray(x) {
    return x.constructor.toString().indexOf("Array") > -1;
}//Returns true if the object prototype contains the word "Array.".
instanceof Operator return true: 
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array     // Return to true

12.JavaScript method toString() converts an array to a comma separated string of array values
13. join() method can also combine all array elements into a string, and split() is the inverse operation

var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * "); 
// Banana * Orange * Apple * Mango

14 the pop() method removes the last element from the array, and the pop() method returns the value of "ejected"

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop();      // The value of x is "Mango" and the original array pops up

15 the push () method (at the end of the array) adds a new element to the array and returns the length of the new array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");       //  Add a new element to fruits
var x =  fruits.push("Kiwi");   //  The value of x is 5

The 16.shift() method removes the first array element and "shifts" all other elements to a lower index. The shift() method returns the string "displaced"
17. The unshift() method (at the beginning) adds new elements to the array and "reverses" the old elements. The unshift() method returns the length of the new array.
18. Relationship:
·pop() and push() act on the end of the array
·shift() and unshift() act on array headers
·pop() and shift() remove, return the removed value
·push() and unshift() add to return the added length
19. JavaScript arrays belong to objects, and the elements in them can be deleted by using the JavaScript delete operator

var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];           // Change the first element in fruits to undefined

It will cause hollowness, not recommended
20. The splice () method can be used to add new items to an array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
//At index 2, delete 0 and insert the following elements. insert
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
//At index 2, delete 2 and insert the following elements. replace

The ability to use splice() to remove elements without leaving "holes" in the array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);        // Remove the first element in fruits

21. The concat () method creates a new array by merging (joining) existing arrays
The concat() method does not change the existing array. It always returns a new array.
The concat() method can use any number of array parameters
22. slice() method cuts out a new array with a fragment of the array. The slice () method creates a new array. It does not remove any elements from the source array. One parameter should be on the right. When there are two parameters, the middle segment of two numbers should be taken.
23. sort() method sorts the array alphabetically
24. reverse() method reverses the elements in the array
25.sort () is used for string sorting by default. When the number is in order, the comparison function should be used to correct it.
Sort ascending:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); 

When comparing 40 and 100, the sort() method calls the compare function (40100). This function evaluates to 40-100 and then returns - 60 (negative). The sort function sorts 40 to a lower value than 100.
Sort descending:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a}); 

26. Random sorting (Application of comparison function)

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()}); 

27. You can use Math.max.apply to find the highest value in the array

function myArrayMax(arr) {
    return Math.max.apply(null, arr);
}
Math.max.apply([1, 2, 3]) Be equal to Math.max(1, 2, 3). 

However, the fastest solution is to use the "home-made" method, where the function traverses the array and compares the highest value found with each value

function myArrayMax(arr) {
    var len = arr.length
    var max = -Infinity;
    while (len--) {
        if (arr[len] > max) {
            max = arr[len];
        }
    }
    return max;
}

To find the minimum value, only Min is needed to replace Max
28. JavaScript arrays often contain objects

var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];

The sort() method can still be used to sort an array, sort it numerically

cars.sort(function(a, b){return a.year - b.year});

Sort by character
cars.sort(function(a, b){

return (a.type.toLowerCase())>=(b.type.toLowerCase())?1: -1;});
  1. Traverse Array.forEach()
    The forEach() method calls a function (callback function) once for each array element
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
  txt = txt + value + "<br>"; 
}

It can be roughly interpreted as: object. forReach (called function)
30. Map Array.map()
The map() method creates a new array by performing functions on each array element.
The map() method does not perform functions on array elements that do not have values.
The map() method does not change the original array.
Including three parameters
• project value
• project index
• array itself

var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
  return value * 2;
}

When not in use, it can be omitted: function myFunction(value)
31. Filter Array.filter()
The filter() method creates a new array containing the elements of the array that passed the test
Including three parameters
• project value
• project index
• array itself

var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
function myFunction(value) {
  return value > 18;
}

32. Reduce Array.reduce()
The reduce() method runs a function on each array element to generate (reduce) a single value.
The reduce() method works from left to right in the array.
The reduce() method does not reduce the original array.
• Total (initial value / previously returned value)
• project value
• project index
• array itself

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value, index, array) {
  return total + value;
}

total starts with the first number, followed by the previous return value.
The reduce() method can accept an initial value: total.
32. Array.reduceRight()
The reduceRight() method runs a function on each array element to generate (reduce) a single value.
The reduceRight() method works from right to left in the array.
The reduceRight() method does not reduce the original array.
This function takes four arguments:
• Total (initial value / previously returned value)
• project value
• project index
• array itself
33. Array.every()
The every() method checks whether all array values pass the test, and the return value is Boolean. Return true if all conditions are met
• project value
• project index
• array itself
34. Test whether there is Array.some()
some() method checks whether some array values pass the test, and the return value is Boolean. Return true if the condition is met
• project value
• project index
• array itself
35. Search Array.indexOf()
The indexOf() method searches the array for element values and returns their positions

array.indexOf(item, start)

item is required. Items to retrieve.
Start is optional. Where to start the search. A negative value starts at the given position at the end and searches to the end.
If the item is not found, Array.indexOf() returns - 1.
If the item appears more than once, returns the location of the first occurrence.
36. Array.lastIndexOf() is similar to Array.indexOf(), but searches from the end of the array
37. Find the first Array.find()
The find() method returns the value of the first array element that passed the test function
• project value
• project index
• array itself

var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);
function myFunction(value, index, array) {
  return value > 18;
}
  1. The findIndex() method returns the index of the first array element that passed the test function
Published 13 original articles, won praise 0, visited 358
Private letter follow

Posted by gregor63 on Mon, 03 Feb 2020 03:30:13 -0800