JavaScript operation array method

JavaScript manipulation of arrays and object methods

splice

splice() method adds/remove items to/from the array, and then returns the deleted item

Syntax: arr.splice(index, arrlength, item1, item2, item3,...itemx)

The parameter
index is required. Integer, which specifies the position of adding/deleting items. Use a negative number to specify the position from the end of the array.
arrlength is required. The number of elements in the array to be deleted. If set to 0, the item will not be deleted.
item1, …, itemX is optional. New items added to the array.

The return value of this method is the item that was deleted or added

<div id="app">
        <!-- 
            声明一个数组   移除数组中所有的元素
            splice  向数组中添加或删除元素
         -->
        <p>{
    
    {
    
    arr}}</p>
        <button @click="removeArr">移除数组中所有的元素</button>
        <button @click="removeArrIndex">移除数组前三个元素</button>
        <button @click="addArr">添加回来</button>
    </div>
    <script>
        const APP = {
    
    
            data() {
    
    
                return {
    
    
                    msg: 'hello Vue3.0!',
                    todo: {
    
    
                        name: 'Tom'
                    },
                    arr: ['1', '2', '3', '4', '5', '6']
                }
            },
            methods: {
    
    
                removeArr() {
    
    
                    this.arr.splice(0, this.arr.length)
                    console.log(this.arr.splice(0, this.arr.length))
                },
                removeArrIndex(){
    
    
                    this.arr.splice(0, 3);
                },
                addArr() {
    
    
                    this.arr.splice(0, 0, '1', '2', '3', '4', '5', '6');
                }
            }
        };
        const app = Vue.createApp(APP);

        app.component('todo-item', {
    
    
            props: ['todo'],
            template: `<li>{
     
     {todo.name}}</li>`
        });
        app.mount('#app');
    </script>

Note: The role of the splice() method is different from that of the slice() method. The splice() method will directly modify the array.

concat

The concat() method is used to concatenate two or more arrays.
This method does not change the existing array, but only returns a copy of the concatenated array.

Syntax arr.concat( arr2, arr3, arrx …)

 arr: ['1', '2', '3', '4', '5', '6'],
 arr2: ['Tom', 'Jerry', 'speike']

arrConcat () {
    
    
    this.concatArr = this.arr.concat(this.arr2)  
    //  [ "1", "2", "3", "4", "5", "6", "Tom", "Jerry", "speike" ]
     返回值需要一个变量来接收
}
	

join

join() divides the data by the specified character and returns a string.

Syntax: arr.join (delimiter)

arr: ['1', '2', '3', '4', '5', '6']

arrJoin() {
    
    
   this.joinArr = this.arr.join('-');
   // 1-2-3-4-5-6
   返回值需要一个变量来接收
}

pop

porp() deletes the last object of the array and returns the value of the deleted element

 arr: ['1', '2', '3', '4', '5', '6'],
  arrPop(){
    
    
      this.popArr = this.arr.pop();
       // 6  
       会改变原数组, 且返回被删除的元素
}

push

The push() method adds one or more elements to the end of the array and returns the new length.

Syntax: array.push(newObject1,newObject2,...);

arr: ['1', '2', '3', '4', '5', '6']
arrPush(){
    
    
 	this.pushArr = this.arr.push(1);
 	// 7   返回值是追加后数组的长度 length
}

shift

The shift() method is used to delete the first element of the array and return the value of the first element.

Syntax: arr.shift( ))

arr: ['1', '2', '3', '4', '5', '6']
arrShift(){
    
    
   this.arrShift = this.arr.shift();
   // [ "2", "3", "4", "5", "6" ]
 }

slice

The slice() method can return selected elements from an existing array. This operation does not modify the data of the original array

Syntax: arr.slice(start, end) The
parameter
start is required. Specify where to start selection. If it is negative, it specifies the position from the end of the array. In other words, -1 refers to the last element, -2 refers to the penultimate element, and so on.
end is optional. Specify where to end the selection. This parameter is the array index at the end of the array fragment. If this parameter is not specified, the segmented array contains all elements from start to the end of the array. If this parameter is a negative number, then it specifies the elements counted from the end of the array.

arr: ['1', '2', '3', '4', '5', '6'],
sliceShift() {
    
    
     this.sliceArr = this.arr.slice(0, 5)
 }

sort

The sort() method is used to sort the elements of the array, sorting the array items in ascending order-that is, the smallest value is at the top, and the largest value is at the bottom.

Syntax: arr.sort( fn) The
parameter fn is optional and must be a function

When sorting, the sort() method calls the toString() transformation method of each array item, and then compares the resulting strings to determine how to sort. Even if each item in the array is a numeric value, the sort() method compares strings, so the following situation will occur:


var arr1 = ["a", "d", "c", "b"];
console.log(arr1.sort()); // ["a", "b", "c", "d"]
arr2 = [13, 24, 51, 3];
console.log(arr2.sort()); // [13, 24, 3, 51]
console.log(arr2); // [13, 24, 3, 51](原数组被改变)

In order to solve the above problems, the sort() method can receive a comparison function as a parameter, so that we can specify which value is in front of which value. The comparison function accepts two parameters. If the first parameter should be before the second, it returns a negative number, if the two parameters are equal, it returns 0, and if the first parameter should be after the second, it returns a positive number. The following is a simple comparison function:

function compare(value1, value2) {
    
    
	if (value1 < value2) {
    
    
		return -1;
	} else if (value1 > value2) {
    
    
		return 1;
	} else {
    
    
		return 0;
	}
}
arr2 = [13, 24, 51, 3];
console.log(arr2.sort(compare)); // [3, 13, 24, 51]

Is also equivalent to this

function compare(a,b){
    
    
   return a-b;
}

If you need to use the comparison function to produce descending sort results, just exchange the values ​​returned by the comparison function:

function compare(value1, value2) {
    
    
	if (value1 > value2) {
    
    
		return -1;
	} else if (value1 > value2) {
    
    
		return 1;
	} else {
    
    
		return 0;
	}
}
arr2 = [13, 24, 51, 3];
console.log(arr2.sort(compare));	// [51, 24, 13, 3]

reverse

reverse(): Reverse the order of array items


var arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13](原数组改变)

indexOf() lastIndexOf()

indexOf() : Receives two parameters: the item to be searched and (optional) the index indicating the starting point of the search. Among them, search backward from the beginning of the array (position 0).
lastIndexOf : receives two parameters: the item to be searched and (optional) the index indicating the starting point of the search. Among them, search forward from the end of the array.

Both of these methods return the position in the array of the item to be found, or return 1 if it is not found. When comparing the first parameter with each item in the array, the congruence operator is used

var arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5)); //2
console.log(arr.lastIndexOf(5)); //5
console.log(arr.indexOf(5,2)); //2
console.log(arr.lastIndexOf(5,4)); //2
console.log(arr.indexOf("5")); //-1

forEach()

forEach() traverses the array and runs the given function for each item in the array. This method has no return value. The parameters are all of the function type, and there are parameters by default. The parameters are: the content of the traversed array; the index of the corresponding array, the array itself.


var arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
    
    
	console.log(x + '|' + index + '|' + (a === arr));
});
// 输出为:
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true

map()

map() : Refers to "mapping", run a given function on each item in the array, and return an array composed of the results of each function call.
In actual use, it is similar to the forEach() method

var arr = [1, 2, 3, 4, 5];
var arr2 = arr.map(function(item){
    
    
return item*item;
});
console.log(arr2); //[1, 4, 9, 16, 25]

map() method compared with forEach() method

Same point

  • Are looping through each item in the array

  • Each time the anonymous function is executed, three parameters are supported, the current item in the array, the index of the current item, and the original array input

  • The this in anonymous functions refers to window

  • The this in anonymous functions means that window can only traverse the array

  • Can only traverse the array

About forEach

No return value

arr[].forEach(function(value,index,array){
    
    
	xxxxx
})
  • Parameters: the current item in the value array, index the index of the current item, the original array of array;

  • There are several items in the array, then the anonymous callback function passed in needs to be executed several times

  • In theory, this method has no return value. It just traverses each item in the array without modifying the original array, but you can modify the original array through the index of the array yourself.

Example:


let arr = [ 1, 2, 3, 4, 5 ];
let res = arr.forEach((item,index)=>{
    
    
	item[index] = item * 10;
});

console.log(res)  // undefined;
console.log(arr);  //  原数组改变 [100,340,570,430,760];

About map()
has a return value


arr.map(function(value,index,array){
    
    
	xxx
	return xxx
});
  • Parameters: the current item in the value array, index the index of the current item, the original array of array
  • Difference: The return value is supported in the callback function of map, and the data returned is equivalent to copying this item in the array

Example


var array = [10,34,57,43,76];  
var res = array.map(function (item,index,input) {
    
      
       return item*10;   
})  
console.log(res);  // [100,340,570,430,760];
console.log(array);  // 原数组不会改变

filter()

filter() : "Filter" an array, each item in the array runs a given function and returns an array that meets the filter conditions.


var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arr2 = arr.filter(function(x, index) {
    
    
	return index % 3 === 0 || x >= 8;
}); 
console.log(arr2); //[1, 4, 7, 8, 9, 10]

every()

every() : Judge whether each item in the array meets the condition, only if all items meet the condition, will it return true.


var arr = [1, 2, 3, 4, 5];
var arr2 = arr.every(function(x) {
    
    
	return x < 10;
}); 
console.log(arr2); //true
var arr3 = arr.every(function(x) {
    
    
	return x < 3;
}); 
console.log(arr3); // false

some()

some() : Determine whether there is an item that meets the condition in the array, as long as one item meets the condition, it will return true.


var arr = [1, 2, 3, 4, 5];
var arr2 = arr.some(function(x) {
    
    
	return x < 3;
}); 
console.log(arr2); // rue
var arr3 = arr.some(function(x) {
    
    
	return x < 1;
}); 
console.log(arr3); // false

Guess you like

Origin blog.csdn.net/weixin_52400118/article/details/109897905