当前位置:网站首页>JS array method

JS array method

2022-06-13 08:37:00 Medlar plus

Conventional methods
toString() Convert an array to an array value ( Comma separated ) String . When the original value is needed ,JS Will automatically convert the array to a string .
join(param) and toString be similar , The difference is that param As a separator

Additions and deletions
pop() Delete the last element , Return the deleted value
push() Add an element at the end , Returns the length of the new array
shift() Delete the first array element , And move the following elements forward , Returns the deleted element
unshift() Add a new element at the beginning of the array , Move the entire array back , Returns the length of the new array
arr[index] = newValue Array index Modification of index corresponding value
arr[arr.length] = newVal Append a new element to the end of the array
delete arr[index] Clear the element corresponding to the specified index , Will leave undefined holes in the array , Not recommended .

Mosaic array

splice(index,num,[param1],[]...)   from index Location , Delete num Elements , And insert param1,param2 Equal elements 
// The index is 2 Start inserting two elements 
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
// Delete index subscript 2 The first two elements , And splicing 
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
// Remove elements 
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);        // Delete  fruits  The first element in 

concat(arr1, arr2)
Merging multiple array elements returns a new array

var arr1 = ["Cecilie", "Lone"];
var myChildren = arr1.concat(["Emil", "Tobias", "Linus"]); 

slice(index1,[index2])
Crop from index The index position starts at index2( It doesn't contain index2) And returns a new array

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);  //"Orange", "Lemon", "Apple", "Mango"

Array sorting
**sort()**
Sort the array elements alphabetically , Will directly affect the order of the original array
**reverse()**
Invert elements in an array , Will directly affect the order of the original array
Expand :sort() function Support custom comparison functions , It is convenient to support sorting in addition to alphabetical order , Other ways can be supported , As follows :

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
    return a - b});  // Sort the numbers in descending order , The result is [1, 5, 10, 25, 40, 100]
points.sort(function(a, b){
    return b - a});  // Sort from large to small 
points.sort(function(a, b){
    return 0.5 - Math.random()});  // Sort in random order 
Math.max.apply(null, arr); // Gets the maximum value of the array 
Math,min.apply(null, arr); // Get the minimum value of the array 

Get the maximum value manually 、 minimum value

function myArrayMax(arr) {
    
    var len = arr.length
    var max = -Infinity; // - infinity 
    while (len--) {
    
        if (arr[len] > max) {
    
            max = arr[len];
        }
    }
    return max;
}

function myArrayMin(arr) {
    
    var len = arr.length
    var min = Infinity;
    while (len--) {
    
        if (arr[len] < min) {
    
            min = arr[len];
        }
    }
    return min;
}

Array traversal
for loop

Use temporary variables , Cache the length , Avoid getting array length repeatedly , When the array is large, the optimization effect will be more obvious .

for(j = 0,len=arr.length; j < len; j++) {
    
    
}

foreach loop
Traverse every item in the array , no return value , It has no effect on the original array , I won't support it IE

//1  no return value 
arr.forEach((item,index,array)=>{
    
    // Execute code 
})
// Parameters :value The current item in the array , index Index of current item , array The original array ;
// There are several items in the array , Then the anonymous callback function passed in needs to be executed several times ;

map loop
map In the callback function of return Return value ;return What is it , It's equivalent to changing this item in the array into something ( Does not affect the original array , It's just like cloning a copy of the original array , Change the corresponding item in the array of the clone )

javascript
arr.map(function(value,index,array){
    
  //do something
  return XXX
})

var ary = [12,23,24,42,1]; 
var res = ary.map(function (item,index,ary ) {
     
    return item*10; 
}) 
console.log(res);//-->[120,230,240,420,10];  A copy of the original array , And it was modified 
console.log(ary);//-->[12,23,24,42,1];  The original array has not changed 

forof Traverse
Can respond correctly break、continue and return sentence

for (var value of myArray) {
    
console.log(value);
}

filter Traverse
It doesn't change the original array , Return a new array

var arr = [
  {
     id: 1, text: 'aa', done: true },
  {
     id: 2, text: 'bb', done: false }
]
console.log(arr.filter(item => item.done))

//  To ES5
arr.filter(function (item) {
    
  return item.done;
});
var arr = [73,84,56, 22,100]
var newArr = arr.filter(item => item>80)   // Get the new array  [84, 100]
console.log(newArr,arr)

every Traverse
every() Is to run the given function for each item in the array , If the function returns true, Then return to true.

var arr = [ 1, 2, 3, 4, 5, 6 ]; 
console.log( arr.every( function( item, index, array ){
     
        return item > 3; 
    })); 
false

some Traverse
some() Is to run the specified function for each item in the array , If the function returns true, Then return to true.

var arr = [ 1, 2, 3, 4, 5, 6 ]; 
   
    console.log( arr.some( function( item, index, array ){
     
        return item > 3; 
    })); 
true

Summary reference :https://www.w3school.com.cn/js/index.asp

原网站

版权声明
本文为[Medlar plus]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270539357962.html