Hahaha, here is just a summary for everyoneThe related methods of arraysOh~
You can check the information for more detailed and in-depth information~ You can save it for easy reference later, and follow a wave of bloggers by the way!!!!~~~~~
Table of contents
1. Search/convert/splice/intercept
1. Find the element indexOf() lastIndexOf()
2. Array and string conversion
(1) Convert array into string join() and toString()
(2)Convert string to array split('separator')
3. String splicing and interception concat() splice()
2. Array addition and deletion functions
1. Addition and deletion of array elements
2.splice() adds, replaces, and deletes elements from an array
1. Reverse the order of elements in the array reverse()
2. Sort the elements in the array, sort()
1. Iterator method that does not generate a new array
2. Iterator method to generate new array
5. Accumulation methods reduce and reduceRight
1.Usage of reduce and reduceRight:
(3) Find the maximum value of the array
6. Array type judgment Array.isArray (array name) judges whether it is an array;
7. The length of the array array name.length
8. Delete the specified element of the array delete array name [index]
Array methods
1. Search/convert/splice/intercept
1. Find the element indexOf() lastIndexOf()
indexOf()
Syntax: Array name.indexOf("element")
Purpose: is used to find whether the element exists in the array. If it is included, it returns the subscript (index) of the element in the array. If it is not included, it returns -1< /span>
Code:
<script>//indexOf
var arr = ["a", "b", "c", "d", "e"];
console.log(arr.indexOf("a"));//0
console.log(arr.indexOf("c"));//2
console.log(arr.indexOf("h"));//-1
</script>
lastIndexOf()
Syntax: Array name.lastIndexOf("element")
Purpose: is used to find the subscript (index) of the last occurrence of an element in the array. If the element is not found, -1 is returned
Code:
<script>//lastIndexOf
var arr = ["a", "b", "c", "a", "b", "c", "d", "e"];
console.log(arr.lastIndexOf("a"));//3
console.log(arr.lastIndexOf("c"));//5
console.log(arr.lastIndexOf("h"));//-1
</script>
2. Array and string conversion
(1) Convert array into string join() and toString()
join()
Syntax: Array name.join("connector")
Purpose: Returns a string containing all elements of the array. Each element is separated by a connector. If no connector is set, it will be separated by commas by default.
toString()
Syntax: Array name.toString()
Purpose:Returns a string containing all elements of the array, separated by commas.
Code:
<script>//join()
var arr =["a", "b", "c", "a", "b", "c", "d", "e"];
var arr_str = arr.join("-");
console.log(arr_str);//a-b-c-a-b-c-d-e
console.log(typeof arr_str);//string
arr_str = arr.toString();
console.log(arr_str);//a,b,c,a,b,c,d,e
console.log(typeof arr_str);//string
</script>
(2)Convert string to array split('separator')
split('separator')
Syntax: Array name.split('separator')
Purpose:Divide the string into several parts through the delimiter, and save each part as an element in a newly created array.
Code:
<script> //split("分隔符")
var sentence = "关注一下博主吧 哈哈哈哈";
//通过空格将字符串分离成数组[]
// ['关注一下博主吧', '哈哈哈哈']
console.log(sentence.split(" "));
//将字符串每个元素分离成数组[]
//['关', '注', '一', '下', '博', '主', '吧', ' ', '哈', '哈', '哈', '哈']
console.log(sentence.split(""));
</script>
3. String splicing and interception concat() splice()
(1) concat() splicing
Syntax: Array.concat(array1,array2,.....)
Purpose:Merge multiple arrays and create a new array. The arrays in the brackets are spliced to the end of the array in front of concat in order
Code:
<script>//concat()
var arr = ["关", "注"];
var arr1 = ["一", "下"];
var arr2 = ["博主", "吧"];
console.log(arr.concat(arr1, arr2));
//['关', '注', '一', '下', '博主', '吧']
</script>
(2) splice() interception
Syntax: Array name.splice(index subscript, length interception length)
Purpose:Intercept a subset of an array to create a new array, (return an array)
Code:
<script>//splice()
var arr = ["a", "b", "c", "a", "b", "c", "d", "e"];
console.log(arr.splice(2,4));//['c', 'a', 'b', 'c']
</script>
2. Array addition and deletion functions
1. Addition and deletion of array elements
(1) push():
Adds one or more elements to the end of the array and returns the length of the new array;
(2) pop():
Remove the last element of the array and return the removed element;
(3) unshift():
Adds one or more elements to the beginning of the array and returns the length of the new array;
(4) shift():
Delete the first element of the array and return the deleted element;
Code:
<script>
var arr = ["a", "b", "c", "d", "e"];
console.log(arr.push("f"));//返回在结尾添加元素后的数组的长度 6
console.log(arr.pop());//返回删除的最后一个元素 f
console.log(arr.unshift("0"));//返回在开头添加元素后的数组长度 6
console.log(arr.shift());//返回删除的第一个元素 0
</script>
2.splice() adds, replaces, and deletes elements from an array
(1) Add:
arr1.splice(startIndex, 0, arr2), note that the second parameter is 0: add to the front
Code:
<script>
var arr = ["1", "1", "1", "1", "1"];
//添加元素 arr1.splice(startIndex,0,arr2) 注第二个参数为0:往前边前边添加
console.log(arr.splice(2, 0, "2", "2", "2"));//返回空数组(后面会讲到,返回删除的元素)
console.log(arr);//['1', '1', '2', '2', '2', '1', '1', '1']
</script>
(2) Replacement:
arr1.splice(startIndex, length, arr2), note that the second parameter is the length of the array to be replaced
Note:The length of deletion must be the same as the number of elements added later
Code:
<script>
var arr = ["a", "b", "c", "d", "e"];
//替换元素 arr1.splice(startIndex,length,arr2),注第二个参数为被替换的数组长度
console.log(arr.splice(2, 2, "2", "2"));//返回删除(被替换)的元素['c', 'd']
console.log(arr);// ['a', 'b', '2', '2', 'e']
</script>
(3) Delete:
The arr.splice(startIndex,length) method deletes elements from the array and returns an array composed of the deleted elements.
Code:
<script>
var arr = ["a", "b", '2', '2', "c", "d", "e"];
console.log(arr.splice(2, 2));//['2', '2']
</script>
3. Sorting of Arrays
1. Reverse the order of elements in the array reverse()
arr.reverse()
Code:
<script>
var arr = ["a", "b", "c", "d", "e"];
console.log(arr.reverse());// ['e', 'd', 'c', 'b', 'a']
</script>
2. Sort the elements in the array, sort()
sort()
Numbers are sorted by size, letters are sorted by alphabetical order
Uppercase letters are smaller than lowercase letters,
Strings, or numerical comparisons of several digits are compared bit by bit according to the subscripts (unicode code)
Code:
<script>
var names = ['Ana', 'ana', 'john', 'John'];
console.log(names.sort());
var nums = [3, 1, 2, 100, 4, 200];
nums.sort();
console.log(nums);
</script>
4. Iterator method
1. Iterator method that does not generate a new array
(1) forEach
Runs the given function on each item in the array. There is no return value. It has the same result as using a for loop.
<script>
function square(num) {
console.log(num * num);
}
var nums = [1, 2, 3, 4];
nums.forEach(square);
</script>
(2) every()
Run the given function on each item in the array. If the function returns true for each item, it returns true; otherwise, if one of the values is false, it returns false (default returns false).
<script>
function isEven(num) {
return num % 2 == 0;
}
var nums = [2, 3, 4, 6, 8, 10];
var even = nums.every(isEven);
console.log(even);//false
</script>
(3) some()
Runs the given function on each item in the array, returning true if the function returns true for any item (default returns false).
<script>
function isEven(num) {
return num % 2 == 0;
}
var nums = [1, 3, 5, 7, 8, 9];
var someEven = nums.some(isEven);
console.log(someEven);//true
</script>
2. Iterator method to generate new array
(1) map()
Runs the given function on each item in the array, returning an array of the results of each function call.
<script>
function square(num) {
return num * num;
}
var nums = [1, 2, 3, 4];
console.log(nums.map(square)); // [1, 4, 9, 16]
</script>
(2) filter()
Pass in a function that returns a Boolean type.
<script>
function isEven(num) {
return num % 2 == 0;
}
var nums = [2, 3, 4, 6, 8, 10];
var evens = nums.filter(isEven);
console.log(evens);//[2, 4, 6, 8, 10]
</script>
Extension: In addition to using the array name.xxx (function method name) to pass parameters to external functions, the above iterator method can also construct an anonymous function. The format is as follows. Here is an example of forEach:
Extension: Anonymous functions
nums.forEach(function (item, index, array) {})
item refers to the element valueindex refers to the element index
Array refers to the array itself
The position of the formal parameters is fixed
5. Accumulation methods reduce and reduceRight
reduce operate from left to right
reduceRight Operation from right to left
Use the specified function to combine array elements and generate a value, receiving two parameters.
1.Usage of reduce and reduceRight:
<script> var numbers = [1, 2, 3, 4, 5, 6, 7,8, 9, 10]; numbers.reduce(function (previousValue, currentValue, index, array) { return previousValue + currentValue; }, initialValue); </script>
in:
Parameter 1: The function to be executed has a return value. The parameters processed inside the function are as follows
previousValue: The value returned by the last callback call, or the provided initial value (initialValue)
currentValue: The currently processed element in the array
index: The index of the current element in the array
array: the array on which reduce is called
Parameter two: the default value passed to the function, which can be ignored
understand:
[x1, x2, x3, x4].reduce(f) = f( f( f (x1, x2), x3), x4)
2.Extended usage
(1) Accumulation
<script>
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var n = a.reduce(function (x, y) { console.log(x + y); return x + y; }, 0);
//0表示函数的默认起始值,即第一次执行0将被赋值给previousValue;
console.log(n);//55
/* 0+1=1
1+2=3;
3+3=6
6+4=10
10+5=15
15+6=21
21+7=28
28+8=36
36+9=45
45+10=55 */
</script>
(2) Accumulation
<script>
var a = [1, 2, 3];
var m = a.reduce(function (x, y) { return x * y; }, 1)
console.log(m);//6
</script>
(3) Find the maximum value of the array
<script>
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var max = a.reduce(function (x, y) { return x > y ? x : y; });
console.log(max);//10
</script>
6. Array type judgment Array.isArray (array name) Judge whether it is an array;
Array.isArray (array name): Determine whether it is an array;
<script>
var a = [1, 2];
//数组是特殊的对象类型
//typeof 判断类型
console.log(typeof a);//object
//isArray 判断是不是数组
console.log(Array.isArray(a)); //true
//instanceof 判断类型
console.log(a instanceof Array); //true
var b = { x: 1, y: 2 };
console.log(Array.isArray(b)); //false
</script>
7. The length of the array Array name.length
Array name.length:Get the number of elements of the array
<script>
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(a.length);//10
</script>
8. Delete the specified element of the array delete array name [index]
delete array name [index]:Delete the specified element in the array, index is the subscript of the deleted element
Note: The principle of deletion in this method is to change the element at that position to undefined, and the length of the array remains unchanged.
<script>
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
delete a[0]; // 把 fruits 中的指定元素改为 undefined
console.log(a);//数组的长度不变
</script>