Chapter 4: Analyzing array reference types

Array reference type analysis

1. Common operations on arrays:

1. Increased:

Array.push() adds dataArray.unshift() pushes data in from the frontCopy the code

2. Delete the:

Array.pop() deletes dataArray.shift() deletes data from the frontArray.splice(1.1."houdunren")
Copy the code

3. The change:

Array.splice(1.1."houdunren")
Copy the code

4. Check:

Array.indexof()

Array.lastindexof()

Array.include

Array.find(function(itme))

Array.findIndex(function(item)) 
Copy the code

5. Testing:

ArrayThe isArray () methodCopy the code

6. Operation:

Array.every(functiom(item,indexArray))

Array.some(functiom(item,indexArray))

Array.filter(functiom(item,indexArray))

Array.map(functiom(item,indexArray),this)
// This refers to passing the current scope to the map callback function

Array.reduce(functiom(pre,item,index,Array)
Pre defaults to the first value of the array

Array.forEach(function(item,indexArray))

Array.from(The array-like or iterable method creates a new, shallow-copy instance of an arrayCopy the code

7. Order:

Array.sort(function(a,b){
    return a-b;
})
Copy the code

2. Multidimensional array manipulation

const ary = [1.2]
ary[1] = 99

Copy the code

And that’s successful, because the array is a reference, const as long as it doesn’t change the memory address and we’re operating on the value below the same memory address, so JS doesn’t get an error

3.Array.of and Array creation details

If no value is set, undefined

const ary = ["houdunren.com"]
ary[3] = "hdcms"The value of the array1.2The value ofundefined
Copy the code
let ary = new Array(6) creates a value of length6To create an array containing the number six, we provideArrayOf methodslet ary = Array.of(6)               / / [6]
Copy the code

4. Type detection and conversion

Array. The isArray () method

5. Expand grammar and assign value to deconstruct

let ary = [1.2.3.5]
let hd = [6.7]
let aryhd = [...ary,...hd]
Copy the code

6. Dot syntax manipulates DOM elements

const divs = document.querySelectAll("div"); Get all div NodeList [...divs] and convert NodeList to an arrayCopy the code

7. Use deconstructed assignment for efficiency

Note: left and right structures must be the sameconst ary = ["hdcs"."tsy"."tly"]
const [ary1,ary2,ary3] = [...ary];

Copy the code

8. Various manipulation techniques for adding elements

const ary = [1.2.3]

(1)ary[ary.length] = "hdms"

(2) Majority group expansion syntax (3)ary.push()
Copy the code

9. Data loading and unloading and filling operations

10. Array manipulation:

Array.push(data) Pushes dataArray.pop(data) Displays dataArray.shift(data) Pops data from the frontArray.unshift(data) Pushes data from the frontArray(5).fill("data"Create an array of five data [1.2.3.5.4].fill("data",begin,end)
Array.concat() joins after// A more flexible approach
Array.slice(begin,end)          
// This method does not alter the original array, but creates a new copy of the array

Array.splice(begin,number,addData)
// This method directly changes the original array, the third is the data to be added

// Find (same as string retrieval) :

Array.find(function(item) // Reference type lookup, if found, returns the value (no index is returned)Array.findIndex(function(item)) // Returns the index valueArray.indexOf()
Array.lastindexof()
Array.includes!!!!!!!!!! Note:const ary= [5,1,2,8,6, [1, 2]]console.log(ary.includes([1.2])); returnfalse, because the reference type compares memory addresses and the array is a special objectfalse(The difference between value type and reference type, memory space is not the same)const ary = [1.2.3.4]
ary.splice(1.1."houdunren")
console.table(ary) Empties the array:const ary = [1.2.23.5]
ary.length = 0;                 // Change the original array
ary = [];                       // Create new memory space
Copy the code

11. Array move function instance

const ary = [1.2.3.4.6];

function move(array,from,to){
    if(from < 0 || to > array.length){
        console.error("Parameter error");
        return;
    }
    const newArray = [...array];
    let item = newArray.splice(from.1)
    newArray.splice(to,0. item);return newArray;
}

console.log(move(ary,1.3))

Copy the code

12. Basic principle of array includes method

let ary = [1.2.3.5.8.4]
function includes(array,findItem){
    for(const value of array){
        if(value === findItem) return true;
    }
    return false;
}
Copy the code

13. The use of array sort skills

const ary = [5.1.2.8.6]
let ary2 = ary.slice()
ary2 = ary2.sort(function(a,b){
    // A-b from small to large b-A from large to small
    return a-b;
})
console.log(ary2);
Copy the code
Sort principlelet ary = [8.5.74.6.5.1]
function sort(array){
    for (const n in array) {
        for(const m in array){
            if(array[n] < array[m]){
                lettemp = array[m]; array[m] = array[n]; array[n] = temp; }}}return array;
}
console.log(sort(ary));

Copy the code

14. Every () and some ()

For example, search for user input values that contain keywords

Every (): all are satisfiedfunctionConditional returntrue

const ary = [
    {name:"tsy".js:89},
    {name:"tly".js:86},
    {name:"tzy".js:55}]let res = ary.every(function(item){
    return item >= 60;
})
console.log(res ? "All students passed." : "Some students failed.") some(): Returns true if any of them return truelet res = ary.some(function(item,index,arr){
    console.log(item);
    return false;
})

Copy the code

15. Filter Use of filter elements

Filter (): This element is taken if true is returned

let lessons = [
    {name:"PHP Learning Course".type:"php"},
    {name:"PHP Learning Course 2".type:"php"},
    {name:"Mysql Learning Course".type:"mysql"}]// Find the class whose type is PHP
let res = lessons.filter(function(item,index,arr){
    return item.type == "php";
})
console. The table (res) principle:let ary = [1.2.3.4]
function filter(array,item){
    let newAry = [];
    for (const value of array) {
        // If not, push the new array
        if(item.includes(value) == false) newAry.push(value)
    }
    return  newAry;
}
console.log(filter(ary,[2.3]))

Copy the code

Map array and reference types

When processed with map(), copies of value types are created and reference types modify the original data

let lessons = [
    {name:"PHP Learning Course".type:"php"},
    {name:"PHP Learning Course 2".type:"php"},
    {name:"Mysql Learning Course".type:"mysql"}]let data = [1.2."houdunren"]
data.map(function(item,index,array){
    item = Dye - ` long${item}`;
})
lessons.map(function(item){
    item.click = 100;
})
console.log(lessons);
console.table(data)

Copy the code

17. Super easy to use reduce method detailed explanation

reduce(function(pre,item,index,array))

When no second argument is passed:

  • The first time pre is the first value of the array and item is the second value of the array
  • The second pre is the return value of the function, and item is the third value of the array

Pass the second argument:

  • Pre is the second argument, and the second is the return value of the function
1.Count the number of elements in an array using reduce:let ary = [1.5.1.8.5.3.8.5]

function itemCount(array,findItem){
    return array.reduce(function(total,item){
        total += findItem==item ? 1 : 0;
        return total;
    },0);
}


2.Use reduce to get the maximum value in the array:let ary = [1.5.1.8.5.3.8.5.11]

function maxInt(ary){
    return ary.reduce(function(maxInt,item){
        returnmaxInt > item ? maxInt : item; })}console.log(maxInt(ary))

console.log(itemCount(ary,1));
Copy the code

18. Get items in the shopping cart whose prices are in a certain range

let cart = [
    {name:"iphone".price:12000},
    {name:"iMac".price:5000},
    {name:"computer".price:50000},
    {name:"ipad".price:11000}]function getRange(number,array){
    return array.reduce(function(pre,item){
        item.price > number ? rangeAry.push(item.name) : rangeAry.push()
        returnrangeAry; }}, [])console.log(getRange(10000,cart));

Copy the code

19. Deduplicate the reduce array

let ary = [1.2.5.6.2.5]

function getRepeat(ary){
    return ary.reduce(function(pre,item){
        if(pre.includes(item) == false){
            pre.push(item)
        }
        returnpre; }}, [])console.log(getRepeat(ary));

Copy the code

20. Cool text LOGO effect element construction

let divs = document.getElementsByTagName("div") [0];
let div_content = [...divs.textContent];

function logo(){
    div_content.reduce(function(pre,cur,index){
        if(pre == index){
            (divs.innerHTML == ' ');
        };
        
        let span = document.createElement("span");
        span.innerHTML = cur;
        divs.appendChild(span);
        span.addEventListener("mouseover".function(){
            this.className = "color"; })},0);
}

logo();

Copy the code