This is the 25th day of my participation in the August Challenge
Hi, I’m Ken
Author: Please call me Ken Link: juejin.cn/user/109118… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.
🌊🌈
Part of the content and pictures of the article are from the Internet. If you have any questions, please contact me (there is an official account in the introduction of the home page).
This blog is suitable for just contactJS
And the friends who want to review after a long time.
🌊🌈
5.5_ Array objects
Array objects in JavaScript can be created using new Array or the literal “[]”.
5.5.1_ Array Type Detection
During development, it is sometimes necessary to check whether a variable is of type array. For example, in two numbers. The parameter must be an array, can not pass in other types of value, otherwise error, so this can be used in the function to check whether the type of the parameter is array. There are two common ways to detect Array types, using the instanceof operator and the array.isarray () method.
Example code is as follows:
var arr = [];
var obj = { };
// The first way
console.log ( arr instanceof Array );
// Output result :true
console.log ( obj instanceof Array );
// Output result :false
// The second way
console.log ( Array.isArray(arr) );
// Output result :true
console.log ( Array.isArray(obj) );
// Output result :false
Copy the code
In the above code, a true result indicates that the given variable is an array, and a false result indicates that the given variable is not an array.
5.5.2_ Add or remove array elements
JavaScript array objects provide methods for adding or removing elements. You can add new array elements at the end or the beginning of an array, or remove array elements at the end or the beginning of an array.
Add or remove array elements:
The method name | Functional description | The return value |
---|---|---|
Push (parameter 1…) | Adding one or more elements to the end of an array modifies the array | Returns the new length of the array |
Unshift (parameter 1…) | Adding one or more elements to the beginning of an array modifies the array | Returns the new length of the array |
pop() | Removes the last element of an array, or returns undefined if the array is empty, modifying the array | Returns the value of the deleted element |
shift() | Removes the first element of an array, or returns undefined if the array is empty, modifying the array | Returns the first element value |
Note that the push() and unshift() methods return the length of the new array, while the pop() and shift() methods return the removed array elements.
Case study: Demo
<script>
var arr = ['Rose'.'Lily'];
console.log('Original array :'+ arr);
var last = arr.pop();
console.log('Remove element at end :'+ last + '- Removed array :' + arr);
var len = arr.push('Tulip'.'Jasmine');
console.log('After adding elements at the end, the length becomes :'+ len + '- Add after array :'+ arr);
var first = arr.shift();
console.log('Remove elements at the beginning :'+ first + '- Removed array :' + arr);
len = arr.unshift('Balsam'.'sunflower');
console.log('After adding elements at the beginning, the length becomes :' + len + '- Add after array :' + arr);
</script>
Copy the code
As you can see from the above code, the push() and unshift() methods can add one or more elements to the end or beginning of a specified array, while the POP () and shift() methods can only remove and return one element at the end or beginning of a specified array.
5.5.3_[Case] Filter arrays
Example: Ask to remove the data whose salary is 2000 or above from the array containing salary, and put the data less than 2000 back into the innovative array. The array is [1500,1200,2000, 2100, 1800].
var arr = (1500.1200.2000.2100.1800];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] < 2000) {
newArr.push(arr[1);
// equivalent to: newArr (newarr.length) = arr[I];}}console.log(newArr);
(3) [1500, 1200, 1800]
Copy the code
In the above code, line 1 is the original array arr. Line 2 defines a new array, newArr, to hold data with wages below 2000. Line 3 checks the if statement in the for loop, and if it does, uses push() to store it in a new array, newArr.
5.5.4_ Array Sorting
Array sort can sort array elements or reverse the order of array elements.
Sorting method:
The method name | Functional description |
---|---|
reverse() | Reversing the positions of elements in an array, this method changes the original array and returns the new array |
sort() | Sort the elements of an array. This method changes the array and returns the new array |
Note that the reverse() and sort() methods return the length of the new array.
// Invert the array
var arr = ['red'.'green'.'blue'];
arr.reverse();
console.log(arr);// output result :(3) ["blue", "green","red"]
// The reverse() method is used to reverse array elements.
// Array sort
var arr1 = [13.4.77.1.7];
arrl.sort(function(a, b)
return b - a;// In descending order
});
console.log(arr1);// output: (5) [77,13,7,4,1]
// The sort() method is used to sort the elements from largest to smallest.
Copy the code
return a - b;// In ascending order
Copy the code
5.5.5_ Array Index
During development, to find the position of a specified element in an Array, you can use the retrieval methods provided by the Array object.
Retrieval method:
The method name | Functional description |
---|---|
indexOf() | Returns the first index in the array to which the given value can be found, or -1 if none exists |
lastIndexOf() | Returns the index of the last element in the array, or -1 if none exists |
In each of these methods, the default retrieval starts at the specified array index and is performed in the same way as the “===” operator, which returns a successful result only if it is congruent.
Case: demonstration,
var arr = ['red'.'green'.'blue'.'pink'.'blue'];
console.log( arr.indexOf('blue'));// Output :2
console.log( arr.lastIndexOf('blue'));// Output :4
Copy the code
In the above code, the lastIndexOf() method is used to retrieve the index of the last given value from the specified index position in the array. Unlike indexOf(), the lastIndexOf() method defaults to reverse retrieval, from the end of the array to the beginning of the array.
5.5.6_[Case] Array To remove duplicate elements
Let’s use an example to demonstrate the use of array indexes. Requires the removal of duplicate elements in a set of data. Where the array is [‘ blue ‘, ‘green’, ‘blue’]. The sample code is as follows.
function unique(arr) {
var newArr = [];
// It is used to store non-repeating elements in the array
// Iterate through the array. If an element is repeated, add it to the new array
for(var i = 0; i < arr.length; i++) {
if(newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]); }}return newArr;
}
var demo = unique(['blue'.'green'.'blue']);
console.log(demo);
(4) ["blue","green"]
Copy the code
If yes, add it to the new array, otherwise not. So line 4 if this element checks if it returns -1 then that element is not in the new array.
3 use the new array is not in the new array
5.5.7_ Array conversion to String
To convert an array to a string, use the join() and toString() methods on the array object.
Array to string:
Method names | Functional description |
---|---|
toString() | Convert an array to a string, with commas separating each entry |
Join (‘ delimiter ‘) | Concatenate all the elements of an array into a string |
Case: demonstration,
/ / use the toString ()
var arr = ['a'.'b'.'c'];
console.log ( arr.toString() );
// Output :a,b,c
/ / use the join ()
console.log ( arr.join() );
// Output :a,b,c
console.log ( arr.join(' '));// Output result: ABC
console.log ( arr.join(The '-'));// The output is a-b-c
Copy the code
As you can see from the code above, the join() and toString() methods turn multidimensional arrays into strings, joined by commas by default. The join() method, on the other hand, can specify symbols to join array elements. In addition, when an array element is undefined, null, or an empty array, the corresponding element is converted to an empty string.
5.5.8_ Other Methods
JavaScript provides many other array methods that are also common. For example, fill an array, join an array, intercept an array element, and so on.
Other methods:
The method name | Functional description |
---|---|
fill() | Fills an array with a fixed value for all elements in the specified subscript range |
splice() | Array delete. splice returns a new array of deleted items |
slice() | Array interception, with slice(begin, end), returns a new array of intercepted items |
concat() | Joins two or more arrays, does not affect the original array, returns a new array |
The slice() and concat() methods return a new array after execution without affecting the original array, while the rest of the methods return a new array after execution.
Example: the splice() method adds or removes array elements at the specified location,
var arr = ['sky'.'wind'.'snow'.'sun'];
// Delete two meta cables starting at index 2
arr.splice(2.2);
console.log (arr);
(2) ["sky", "wind"]
// Add the snow element after removing one element from index 1
arr.splice(1.1.'snow');
(2) ["sky", "snow"]
console.log(arr);
// Add array elements from index 1
arr.splice(1.0.'hail'.'sun');
console.log(arr);
(4) ["sky", "hail", "sun", "snow"]
Copy the code
In the code above, the first argument to the splice() method specifies the subscript position to add or remove; The second argument is used to remove the number of elements from the array starting at the specified subscript position. If set to 0, this method adds only elements. The remaining arguments indicate the array element to be added, or if omitted, the element is deleted.
That’s the end of today’s introductory study
Peace
🌊🌈
A Ken HTML, CSS introduction guide (a)_HTML basics a Ken HTML, CSS introduction guide (b)_HTML page elements and attributes a Ken HTML, CSS introduction guide (c)_ text style attributes Ken HTML, CSS introduction guide (four)_CSS3 selector Ken HTML, CSS introduction guide (five)_CSS box model Ken HTML, CSS introduction guide (six)_CSS box model Ken HTML, CSS introduction guide (seven)_CSS box model Ken’s Getting Started with HTML and CSS (8)_CSS box model Ken’s Getting Started with HTML and CSS (9)_ Floating and Positioning Ken’s Getting Started with HTML and CSS (10)_ Floating and Positioning Ken’s getting Started with HTML and CSS (11)_ Floating and positioning Ken’s introduction to HTML and CSS (12)_ The application of forms The introduction to HTML and CSS (13)_ the application of forms (14)_ the application of forms the introduction to HTML and CSS (15)_ the application of forms A Ken HTML, CSS introduction guide (16) _ multimedia technology
Suggest collection 】 【 HTML dry share | challenge the shortest possible time to take you into the HTML (18) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (19) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (20)
Suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (a) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (2) suggest collection 】 【 share | JS dry challenge the shortest time to take you into the JS (3) the share | JS dry Recommended collection 】 challenge the shortest time take you into the JS (4) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (5) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (6) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (7) [JS dry share | suggestion collection] challenges the shortest time take you into the JS (8)
🌊🌈 About postscript:
Thank you for reading, I hope to help you if there is a flaw in the blog, please leave a message in the comment area or add contact information in the home page of the personal introduction of private chat I thank every little partner generous advice
Original is not easy, “like” + “attention” thanks for your support ❤