Basic Operation Section 08 array traversal, a method

First, the concept of an array

1.1 What is an array

An array is an ordered list of data.

  1. Each value in the array is called an element of the array.
  2. Each array element has a position, this position is called the index (subscript, index). Array index is starting from 0
  3. The same array, the type of elements without any restrictions. In other words, the same array can put Number, String, Boolean, Object Object, and so on. It can be placed in any type at the same time. Even elements in the array may be another array (multidimensional array configuration).

It features an array of 1.2 JavaScript

Although each language has such an array of data structures, but JavaScript arrays are very different compared to them.

  1. Length of the array can be changed dynamically.
  2. The same can be stored in an array of different types of data.
  3. Ordered set of data
  4. Each array has a length property represents the number of elements in the array

Second, create an array of

There are two basic ways to create an array: literal way and constructors

2.1 literal way

Array literal: all the elements in square brackets, separated by commas between different elements.

例如:["a", 5, "b"]


//创建一个长度为 3 的数组,并初始化了3 个元素:"abc" "b" "d"
var colors = ["abc", "b", "d"];
//创建一个长度为 0 的空数组数组。里面一个值都没有
var colors = [];
//不要在最后一个元素的后面添加逗号,添加逗号虽然语法没有问题,但是在不同的浏览器可能得到不同的结果
var colors = [5, 6, 7,]; //这样数组的长度可能为 3 也可能为 4。在不同浏览器会得到不同的结果应避免这种创建方式。

2.2 manner constructor

The constructor used when creating an object. Constructor type array Array ()

For example: new Array (array length);

//创建一个长度为 0 的空数组
var colors = new Array();
//创建一个长度为 5 的数组。注意这个时候,只是这个数组的length属性是5,但是数组是这样的:  []  初始值也不是undefined的。
var colors = new Array(5);
//创建一个长度为 3 的数组,并且3个元素分别是 "blue" "red" "green"
var colors = new Array("blue", "red", "green");

note:

  1. Create an array of objects using the constructor when the elements do not add after the last comma, otherwise an error. This is wrong:new Array("a", )
  2. If you only use the constructor pass a Number value, this value must be> = 0, otherwise it will error.
  3. Create an array of objects using the constructor time, new keywords can be omitted. For example: Array (5) this is possible.

Third, access and modify elements in the array

Use an index to access elements in the array.

If the length of the array 5, the array is then indexed 0,1,2,3,4

//创建一个长度为 5 的数据
var arr = [10, 20, 60, 5, 7];
alert(arr[0]);  //获取下标为 0 的元素,  即:10
alert(arr[2]);  //获取下标为 2 的元素,  即:60

//
arr[1] = 100;  //把下标为 1 的元素赋值为100。

Fourth, the length of the array

4.1 Gets length of the array

Each array has a call length attribute indicates the length of the array (ie: the number of elements).

var arr = [10, 20, 60, 5, 7];
alert(arr.length);  //弹出:5

4.2 modify the length of the array

In strongly typed languages ​​in general, the length of the array are fixed, namely: creating an array if successful, can not change the length of the array.

However, JavaScript is a weak type of dynamic language, the length of the array can be dynamically changed as needed during the program run

== array length property is not read-only, but can be modified. ==

  1. Modifying the length of the array to the specified value by setting the value of the length directly.
var arr = ["a", 8, "bc"]; //数组的长度为 3 
arr.length = 6; // 修改数组的长度为 6 
alert(arr.length);  //数组的长度已经被修改为了 6 ,所以此处输出6.
// 下标为 3, 4, 5 的元素的值为undefined的。
alert(arr[3]);  //弹出:undefined的。

arr.length = 2; // 修改数组的长度为 2 ,则下标为 >= 的元素被自动从数组移除。
  1. Dynamically modified by the length of the element to be assigned the last element.
var arr = [4, 6, 8];
// 给下标为 10 的元素赋值为 100.  由于最初长度为 3 ,这个赋值操作完成后,数组的长度会自动增长为11
arr[10] = 100;
alert(arr.length);  // 弹出:11
// 没有赋值的元素默认都为 undefined
alert(arr[5]); //弹出:undefined

alert(arr[20]); //弹出: undefined
alert(arr.length); // 长度仍然为11.  上一行代码仅仅去访问元素,而没有赋值操作,则不会引起数组长度的变化

Fifth, iterate

There are four general methods to iterate:

  1. for loop
  2. for ... in statement
  3. for each method (ES5 new)
  4. for ... of statements (ES6 new)

5.1 Use common for loop through the array

var arr = [50, 20, 10, 5, 15, 6];       
for(var i = 0; i < arr.length; i++){    //数组长度多长,就遍历多少次。  循环变量作为数组的下标
  console.log(arr[i]);
}

5.2 for ... in loop through the array

for-in statement is an accurate statement of iterations can be used to enumerate the properties and elements of an array of objects.

Example:

var arr = [50, 20, 10, 5, 15, 6];
// 每循环一轮,都会把数组的下标赋值给变量index,然后index就拿到了每个元素的下标。 
//注意:这里index是元素的下标,不是元素
//对数组来说,index是从0开始顺序获取下标
for (var index in arr) {
  console.log(index);  //循环输出: 0 1 2 3 4 5
}
//这里var 关键字也是可以省略的,但是不建议省略。
for(i in arr){
  console.log(arr[i]);
}

5.3 for ... each loop through the array

ES5 per array adds a method array.forEach (function), use this method, you can automatically help us through all the elements in the array

var arr = [50, 20, 10, 5, 15, 6];
//调用数组的forEach方法,传入一个匿名函数
//匿名函数接受两个参数:   参数1--迭代遍历的那个元素  参数2:迭代遍历的那个元素的下标
//可以在匿名函数内部书需要的代码
arr.forEach( function(element, index) {
  alert(element);
});

5.4 Use for ... of iterate

ES6 provided a for-of iteration statement to through each element of the array

var arr = [50, 20, 10, 5, 15, 6];  
//需要两个形参,第一个ele表示当前遍历的元素。第二个是要便利的数组
for (var ele of arr) {
  console.log(ele);
}

Sixth, an array of commonly used methods

6.1 Conversion Methods

toString () conversion method:

  • Returns a string comma-separated string array are spliced ​​each value obtained by
<script type="text/javascript">
  var arr = [50, 20, 10, 5, 15, 6];
  alert(arr.toString());  //  50,20,10,5,15,6
  alert(arr);  //  50,20,10,5,15,6   当把一个对象直接给alert,则会调用这个对象的toString方法,然后再输出。
</script>

join () method:

  • toString () method can only be connected using a comma, and join () method can be used to specify a connection connector
<script type="text/javascript">
    var arr = [50, 20, 10, 5, 15, 6];
    alert(arr.join("="));   //  50=20=10=5=15=6
</script>

6.2 stack method

Stack: A data structure. Features: FILO (last out)

Element stored in the call stack to the stack (push), removing an element from the stack is called a stack (pop). The first stack elements in the stack underground, in the top of the stack after stack elements. These two actions are the elements of the stack to operate. Generally stack provides two operations suffice.

JavaScript, the same support as the operation of the stack to operate the array.

<script type="text/javascript">
  var arr = ["张三", "李四", "王五"];
  //向栈中添加元素(最后添加的元素肯定在栈顶)   数组中的元素:"张三", "李四", "王五", "志玲"   
  var len = arr.push("志玲");   //push方法返回添加成功后的数组的长度
  alert(len);  // 弹出:4
  arr.push("a", "b");  //也可以向在push方法中传入多个参数,这样每个参数都会添加到数组中。  栈顶元素是  "b"

  //pop出栈,一次只能出栈一个元素
  var item = arr.pop();  //把栈顶的元素从栈(数组)中移除。并返回移除的这个元素
  alert(item); // 弹出:b
</script>

Description:

  • In fact, the stack is to add new elements to the end of the array

  • Stack is actually the last element in the array is removed from the array

    6.2 queue method

Also a queue data structure. Features: FIFO (First In First Out)

JavaScript, the operation of the array is also provided a method of simulation queue.

  1. Additive element (the unshift) to the head of the queue, the queue element is removed from the head (Shift)
  2. Add elements to the end of the queue, removing elements from the end of the queue

Note: Operation of the tail of the queue does not provide a new method, using the respective push and pop operations can be completed.

<script type="text/javascript">
  //把arr当做队列对待,那么 队列头部元素就是 "张三", 队尾元素就是 "王五"
  var arr = ["张三", "李四", "王五"];
  var firstItem = arr.shift();  //把队首元素从队列中移除,并返回移除的这个元素
  alert(firstItem); //张三
  alert(arr);  // 李四, 王五
  var len = arr.unshift("志玲");  //向队列头部添加元素,并返回添加成功后队列(数组)的长度
  alert("数组长度:" + len);  // 数组长度:3
  alert(arr);  // 志玲, 李四, 王五
  arr.unshift("a", "b");
  alert(arr);  // a, b, 志玲, 李四, 王五
</script>

Inversion of elements in the array 6.3

<script type="text/javascript">     
    var arr = ["张三", "李四", "王五"];
    alert("数组倒置前:" + arr); 
    //对数组元素进行倒置。
    arr.reverse();  
    alert("数组倒置后:" + arr);  
</script>

note:

  • == inversion operations are the original array itself to do the operation, it is the return of the original array object, not a newly created array. ==

6.4 Find the specified index in the array element

indexOf (item): from the front to start looking backward position item first appears

lastIndexOf (item): start from the tail find the location of the first occurrence of item forward

  • If you can not find the element, or -1
<script type="text/javascript">     
    var arr = ["张三", "张三", "李四", "王五", "张三", "李四", "王五"];
    alert(arr.indexOf("张三"));  // 0
    alert(arr.lastIndexOf("张三"));  // 4
</script>

indexOf (item, fromBack): open position from the beginning of the second parameter back to find the position of the first occurrence of item

lastIndexOf (item, fromForward): starting from the position of the second argument of where to find the first occurrence of item forward

<script type="text/javascript">     
    var arr = ["张三", "张三", "李四", "王五", "张三", "李四", "王五"];
    alert(arr.indexOf("张三", 2));  // 4
    alert(arr.lastIndexOf("张三", 3));  // 1
</script>

6.4 acquire new array

  1. arr.concat(arrayX,arrayX,......,arrayX)

The method for connecting two or more arrays. Passing at least one parameter, the parameter can be an array can also be an element.

== Note: This method is a new array returned, did not make any changes in the original array ==

<script type="text/javascript">     
    var arr1 = ["a", "b", "c"];
    //把参数数组与arr1连接起来,并返回连接后的新数组
    var newArr = arr1.concat(["c", "d"]);
    //新数组的长度是 5
    alert(newArr.length);
    //原数组的长度还是 3  。原数组中的元素没有做任何变化
    alert(arr1.length);

    //把两个元素和一个数组与原数组arr1连接起来,并返回新的数组
    var newArr2 = arr1.concat("e", "f", ["g", "h"]);
    //新数组长度为:7
    alert(newArr2.length);  
</script>
  1. arr.slice (start, end): intercepts the array, and returns a new array taken to
  • start: must. From the start of the original starting position in the array taken == (subscript for the element including the start) == . If it is negative, taken from the tail began showing: -1 is the last element
  • end: Optional. == taken to the designated location (subscript for the element not including the end) ==. If not specified, it is referring to the interception of the last element
  • end is greater than the start, or less than interception element

== Note: This method is a new array returned, did not make any changes in the original array ==

<script type="text/javascript">     
    var arr1 = ["a", "b", "c", "d", "e", "f"];
    // 从下标为0的位置开始截取,截取到下标2,但是不包括下标为2的元素. 原数组没有任何的变化
    var newArr = arr1.slice(0, 2);
    alert(newArr);// a, b
    alert(arr1.slice(1, 4)); // b,c,d
    //从下标为2的元素开始截取,一直到最后一个元素
    alert(arr1.slice(2));  //c,d,e,f
    //从倒数第5个元素,截取到倒数第2个
    alert(arr1.slice(-5, -2)); // b c d
</script>
  1. arr.splice (index, howmany, item1, ....., itemX) method to / from the array to add / delete elements, then == return element is removed an array. ==
  • essential. Integer, a predetermined add / remove position of the element, use may be negative at a predetermined position from the end of the array.
  • essential. The number of elements to be deleted. If set to 0, it will not remove elements. If you add an element here should be 0
  • Optional. New projects added to the array.

== Note: This method will make changes to the original array. ==

  • Removing elements
<script type="text/javascript">     
    var arr1 = ["a", "b", "c", "d", "e", "f"];
    //因为第2个参数不为0,所以表示删除元素:从小标为1的位置开始删除,共删除2个元素。(2个中包括下标为1的元素)
    var deleted = arr1.splice(1, 2);    //返回值为删除的元素组成的数组
    //原数组
    alert(arr1);  // a,d,e,f
    alert(deleted); // b,c
</script>
  • Adding elements
<script type="text/javascript">     
    var arr1 = ["a", "b", "c", "d", "e", "f"];
    //因为第2参数为0,所以表示添加元素:从下标为1的位置插入元素。其余的元素会自动向后移动
    var v = arr1.splice(1, 0, "m", "n");    // 因为是添加元素,所以返回的数组长度为 0
    alert(v.length);  // 0
    alert(arr1);    // a,m,n,b,c,d,e,f
</script>

Seven, sort the array

Common sorting algorithm:

Bubbling, select, insert

JavaScript, all of the array object provides a sorting function.

arr.sort (sortby) A method for sorting elements of the array.

  • sortby optional. The provisions of the sort order. It must be a function.
  1. When no incoming parameters, the default is ascending order. However, in ascending order of time, each element is then converted into a string, the coding order sorting table.
<script type="text/javascript">     
    var arr1 = ["a", "ab", "fca", "cd", "eb", "f"];
    arr1.sort();    //默认情况按照编码表中的顺序排列
    alert(arr1);    // a, ab, cd, eb, f, fca

    var arr2 = [10, 8, 6, 20, 30, 15];
    arr2.sort();
    console.alert(arr2); // 10,15,20,30,6,8
</script>
  1. It can be seen from the above, when the array elements are Number, according to the coding table to sort and not in line with our expectations, we want to sort according to the size of the numbers. At this time, we can pass a "comparison function."
<script type="text/javascript">
    /*
        sort方法进行排序的时候,会调用这个函数,来确定谁大谁小,从而来确定他们的位置。
        排序函数的规则:
        1、比较函数必须具有两个参数  num1, num2
        2、若返回值 > 0, 则认为num1 > num2, 排序的时候num1在num2之后
        3、若返回值 == 0,则认为num1== num2,排序的时候两个数的顺序就保持不变
        4、若返回值 < 0, 则认为num < num2,  排序的时候num1在num2之前。

        总结:
        1、若num1 > num2 返回 正数, num1 < num2 返回 负数,则是升序
        2、若num1 > num2 返回 负数, num1 < num2 返回 正数,则是降序
    */
    function sortNumber (num1, num2) {
        //升序
        if(num1 > num2){
            return 1;
        }else if(num1 == num2){
            return 0;
        }else {
            return -1;
        }
    }
    var arr2 = [10, 8, 6, 20, 30, 15];
    arr2.sort(sortNumber);
    console.log(arr2.toString());
</script>
  • Pure digital array, there is a more simple sorting functions.
//升序函数
function sortAsc(num1, num2){
    return num1 - num2;   //num1 > num2 就返回正数
}
// 降序函数
function sortDesc(num1, num2){
    return num2 - num1; //num1 > num2 就返回负数
}

Eight array detection

How to detect an object is not an Array.

  1. Use instanceof operator.
  2. Use Array.isArray (arr) method.

8.1 instanceof operator

JavaScript, instanceof operator returns a Boolean value indicating whether the object is a specific instance of the constructor.

var arr = [];
alert(arr instanceof Array); //true

8.2 Array.isArray(arr) 方法

Array.isArray (arr), if arr is an array, it returns true, false otherwise

var arr = [];
alert(Array.isArray(arr));  //true
alert(Array.isArray("abc"));    // false

Nine, two-dimensional array

If the elements in the array is stored in an array, it constitutes a two-dimensional array.

//数组中的每个元素都是数组,则就是一个二维数组
var towDimArr = [
                  [4, 5], 
                  [7, 8],
                  [50, 9, 10],
                  [5]
                ];
alert(towDimArr.length); //数组的长度为 4

//使用嵌套循环来遍历二维数组。
for (var i = 0; i < towDimArr.length; i++) {
    for (var j = 0; j < towDimArr[i].length; j++) {
      alert(towDimArr[i][j]);
    }
}

Guess you like

Origin blog.csdn.net/weixin_34326558/article/details/90895703