JavaScript array ES5+ES6

Array concept

1. Array is a kind of object data type, and it is also a relatively complex data.

2. One is equivalent to one large space storing multiple small spaces.

3. The difference between arrays and objects defined by {}

A. The data of object{}object is not in order

B. The data in the data is in order

4. An array is a continuous and ordered space in computer memory, which is represented by a variable.

Array definition

A. var arr = [data,data...];

like:

var arr = ['nihao', 'hello', 20]

 console.log(arr);

B.var arr = new Array(data,data...)

like:

 var arr = new Array('nihao', 'hello', 20)

    console.log(arr)

important point:

1. If you use the definition form of [] and put a number, it means that there is only one small space in the current array, and this number is placed in it. If you use new Array (number), it means that there are (numbers) empty small spaces in the current array. space

2. The subscript of the first element of the array is always 0;

3. The subscript of the last element of the array is always the array. length-1

4. Find the length of the array: array.length

Array operations

1. Get array data: array.[subscript];

  var arr = new Array('nihao', 'hello', 20)

    console.log(arr[0])//  -->    nihao

2. Set data: array [subscript] = value (if the subscript exists, the data is modified, if the subscript does not exist, the data is added. If the subscript given is greater than the current array, many empty ones will be created. small space)

 var arr = new Array('nihao', 'hello', 20)

    console.log(arr[8] = 'I am the eighth data')

    console.log(arr)

3. Delete data: delete array[subscript] //array length=value;

console.log(delete arr[3])

    console.log(arr.length = 5)

Array traversal

Loop syntax traversal

 var arr = new Array('nihao', 'hello', 20)

    for (var i = 0; i < arr.length; i++) {

        console.log(arr[i])

    }

It is also possible to traverse using for in, but it is recommended to use a for loop with i=0; to traverse.

Array methods

   1.unshift-add one or more elements to the beginning of the array and return the new length of the array

 var arr=['a','b','c','d']

var l=arr.unshift('l')

  console.log(l)      //5

2. push--add one or more elements to the end of the array and return the length of the array

var v = arr.push('m') //Add one or more elements to the end of the array and return the length of the array

  console.log(arr) //The new length of the returned array

 3. Array.pop() deletes the last element of the array and returns the deleted element.

var dete = arr.pop() deletes the last element of the array and returns the deleted element

        console.log(dete) puts back the deleted elements

4. Array.splice(parameter 1, parameter 2, parameter 3) - add, delete and modify the array

var arr = ['a','b','c']
// Change - Parameter 1: Starting subscript; Parameter 2: Number of deleted elements; Parameter 3: New elements placed at the deleted position - OK It is multiple
arr.splice(1,1,'d') // ['a','d','c']
// Increase
arr.splice(1,0,'d') // ['a ','d','b','c'] - Delete 0 elements, that is, do not delete them, and then put new elements
// Delete - The third parameter can be omitted

arr.splice(1,0) // ['a','c']

5. Array.concat()--Concatenation of arrays

var arr = ['a','b','c'];
var brr = ['d','e','f'];
// Combine arr and brr into a larger array
var crr = arr .concat(brr) // ['a','b','c','d','e','f']
// Concatenate one or more values ​​and arrays into one large array
var crr = arr.concat(1,2,3)//['a','b','c',1,2,3]

6.Array.sort()--sort the array

var arr = [9,5,3,7,1,6,4,8,2];
arr.sort() // Default ascending order
console.log(arr) // [1,2,3,4,5 ,6,7,8,9]
arr.sort(function(a,b){ // a represents the previous number, b represents the following number
    return ab; // Ascending order - if the previous number-the following number > 0 , then swap positions
    return ba; // Descending order - if the following number - the previous number > 0, then swap positions
})

7.Array.reverse() - Reverse of array

var arr = ['a','b','c'];
arr.reverse()
console.log(arr) // ['c','b','a']

8.Array.join() - Join the elements in the array together using the specified connector

var arr = ['a','b','c'];
var str = arr.join('_') // The parameter is the joiner
console.log(str) // a_b_c

var str = arr.join() // By default, commas are used to connect
console.log(str) // a,b,c

var str = arr.join( ' ')
console.log(str) // abc

9. Array.slice() - intercept the array******************************Key points

var arr = ['a','b','c','d','e','f']; // Extract
'b', 'c', 'd' from the array to form New array
var brr = arr.slice(1,4) // Parameter 1 is the starting subscript of interception, parameter 2 is the end subscript of interception, and the result does not include the element corresponding to the end subscript console.log(brr
) // ['b','c','d']
// If the second parameter is omitted, the default is to intercept from the starting index to the end of the array
var crr = arr.slice(1)
console.log(crr) // ['b','c','d','e','f']

In es5, new methods for arrays

1.indexOf()--Find the subscript of the first occurrence of the element in the array. If it is found, it will return the subscript. If it is not found, it will return -1.

 var arr = ['Xiaomi', 'vivo', 'Huawei', 'Apple', 'Xiaomi', 'vivo', 'Huawei', 'Apple']

        console.log(arr.indexOf('Huawei')) //2

2.forEach traverses the array

// Syntax: array.forEach(function(value, index, array){

    // value is the element that is traversed each time

    // index is the subscript corresponding to each element

    //array is the array currently being traversed

// })

// var arr = ['Li Xiaolu', 'Bai Baihe', 'Ma Yili', 'Article', 'Jia Nailiang', 'Wang Baoqiang', 'Yang Mi']

// Traverse this array

// arr.forEach(function(value, index, array) {

//     // console.log(value);

//     // console.log(index);

//     // console.log(array);

// })

// index and array are optional parameters. When traversing, these two parameters can be added or not.

// arr.forEach(function(value) {

//     console.log(value);

// })

// This traversal method has the same effect as using a for loop to traverse. The for loop is encapsulated inside the method, so this method has no return value - undefined

// If you want to stop traversing when a certain value is reached, you can only use a for loop

3.map

 // map: Traverse the array, process each element through the function, process it into a new element, and return all new elements into a new array.

    // Syntax: array.map(function (same parameters as forEach) {

    //     return newValue

    // })

    // Return a new array consisting of all new elements

example:

 var arr = [10, 20, 30]

    // Increase each element by 30%

    var brr = arr.map(function (v) { // The value here is a formal parameter, we can customize the name

        var newValue = v + v * 0.3

        return newValue

    })

    console.log(brr);

 // filter: filter array - traverse the array, combine the elements in the array that meet the specified conditions into a new array and return it

    // Syntax: array.fitler(function (same parameters as forEach) {

    // return condition

    // })

    //Return value: Returns an array composed of all elements that meet the condition

example:

var arr = [85, 90, 68, 45, 93, 21, 58]

    // 将数组中不及格的所有成绩放在新的数组中

    var brr = arr.filter(function (v) {

        return v < 60

    })

    console.log(brr);// [45, 21, 58]

New methods in ES6 (key points)

1.some methods

 some - determines whether at least one element in the array satisfies the condition, and returns a Boolean value

grammar

/*数组.some(function(v,i,a) {
return  条件
} )
语法:array.some(function(item,index,array)
    //item:当前元素的值;
    //index:当前元素的索引;
    // array:当前元素的数组对象;
*/
//判定一个数组是否符合某个条件,如果有一项符合返回true,如果一项都不符合,返回false;
 var arr = [100, 500, 9, 80, 76, 88]
    var k = 0
    var bool = arr.some(v => {
        k++
        return v < 60
    })
    console.log(bool);//true
    console.log(k);//6

2.Array.every method

Determine whether all elements in the array meet the specified conditions and return a Boolean value

 // every - 判断数组中是否所有元素都满足指定条件,返回布尔值
    /*
    语法:  数组.every(function(v, i, a) {
        return 条件
    })
    判定一个数组是否符合某个条件,如果有一项不符合会立即返回flase不在执行,
如果全都符合,会全遍历一遍数组后返回true;
    */
    var arr = [100, 500, 90, 8, 69, 88]
    // 是否所有成绩都及格了
    var k = 0
    var bool = arr.every(v => {
        k++
        return v > 60
    })
    console.log(bool);//flase
    console.log(k);//4

3.Array.find method

  // find - 在数组中找满足条件的第一个元素 - 返回找到的元素,找不到就返回undefined
    /*
    语法:
  
    数组.find(function(v, i, a) {
        return 条件
    })
    */
    var arr = [100, 500, 90, 8, 69, 88]
    var ele = arr.find(v => v < 60)
    console.log(ele);//8

4.Array.findindex method

// findIndex - 在数组中找满足条件的第一个元素的下标 - 返回下标,找不到返回-1
    /*
    语法:
    数组.findIndex(function(v, i, a) {
        return 条件
    })
    */
    var arr = [100, 50, 90, 80, 76, 88]
    // 第一个不及格成绩的下标
    var index = arr.findIndex(v => v < 60)
    console.log(index);

Two sorting

1. Bubble sorting - compare two adjacent elements, and use a loop to arrange the numbers in an array in ascending or descending order

 var arr = [1, 56, 2, 234, 5, 6, 82, 10]

for(var j=0;j<arr.length-1;j++){
// 相邻的元素比较,就是下标i的元素跟下标i+1的元素比较 - 所以循环要比正常的遍历少一次
    for(var i=0;i<arr.length;i++){
      // 如果前面的元素比后面的元素大
        if(arr[i]>arr[i+1]){
             //交换位置
        	var tmp = arr[i]
            arr[i] = arr[i+1]
            arr[i+1] = tmp
        }
    }
}
// 如果要降序排序,就将判断条件中的>改为<即可

2. Select sorting - descending order: first find the maximum value, rank it on the far left, then find the second largest value, move to the left..., it has been sorted and will no longer participate in the comparison.

// 重复代码用循环处理,3个数排2次,4个数排3次
for(var j=0;j<arr.length-1;j++){
    for(var i=j+1;i<arr.length;i++){
        if(arr[j]>arr[i]){
        	var tmp = arr[j]
            arr[j] = arr[i] 
            arr[i] = tmp
        }
    }
}
// 如果要进行降序排列,就将判断条件中的>换成<即可

おすすめ

転載: blog.csdn.net/weixin_45441470/article/details/123490307