一,会改变原数组

1.移除数组末尾最后一项.pop(),返回删除的元素 如果你在一个空数组上调用 pop(),它返回 undefined

let word = ['a', 'b', 'c', 'd'];

let newArr = word.pop();  
console.log(word);      //['a', 'b', 'c']  
console.log(newArr);    //d  

let nullArr = [];  
console.log(nullArr.pop()); //undefined 


        2.在数组末尾添加一个或多个元素.push(),返回修改后数组长度

[javascript] view plain copy

    let word = ['a', 'b', 'c', 'd'];  
    let newArr = word.push('e','f');  
    console.log(word);      //['a', 'b', 'c', 'd', 'e', 'f']  
    console.log(newArr);    //6  
        3.移除数组第一项.shift(),返回移除的元素

[javascript] view plain copy

    let word = ['a', 'b', 'c', 'd'];  
    let newArr = word.shift();  
    console.log(word);      //['b', 'c', 'd']  
    console.log(newArr);    //a  
        4.在数组头部添加一个或多个元素.unshift(),返回修改后数组长度

[javascript] view plain copy

    let word = ['a', 'b', 'c', 'd'];  
    let newArr = word.unshift('11','22');  
    console.log(word);      //['11', '22', 'a', 'b', 'c', 'd']  
    console.log(newArr);    //6  
        5.对数组元素排序.sort(),返回排序后的数组
            默认排序顺序是根据字符串Unicode码点

[javascript] view plain copy

    let fruit = ['cherries', 'apples', 'bananas'];  
    console.log(fruit.sort());       // ['apples', 'bananas', 'cherries']  
      
    let scores = [1, 10, 21, 2];   
    console.log(scores.sort());  
    // [1, 10, 2, 21]  
    // 注意10在2之前,  
    // 因为在 Unicode 指针顺序中"10"在"2"之前  

    let things = ['word', 'Word', '1 Word', '2 Words'];  
    console.log(things.sort());   
    // ['1 Word', '2 Words', 'Word', 'word']  
    // 在Unicode中, 数字在大写字母之前,  
    // 大写字母在小写字母之前.  

    function compare(a, b) {  
        if(a < b) {  
            return -1;  
        }else if(a > b) {  
            return 1;  
        }else {  
            return 0;  
        }  
    }  
    let num = [1, 10, 21, 2];  
    console.log(num.sort(compare)); //[1, 2, 10, 21]  
        6.颠倒数组元素.reverse(),返回颠倒后的数组

[javascript] view plain copy

    let word = ["a", "b", "c", "d"];  
    let newArr = word.reverse();  
    console.log(word);      //["d", "c", "b", "a"]  
    console.log(newArr);    //["d", "c", "b", "a"]  
        7.删除或插入元素.splice(),返回数组删除的项,没有删除的项,返回空数组

[javascript] view plain copy

    var word = ['a', 'b', 'c', 'd'];  
    //删除,前闭后开  
    var newArr = word.splice(0,2);  
    console.log(word);      //["c", "d"]  
    console.log(newArr);    //["a", "b"]  

    //插入,当前数组索引1处插入hello  
    var newArr = word.splice(1,0,'hello');  
    console.log(word);      //["c", "hello", "d"]  
    console.log(newArr);    //[]  

    //替换  
    var newArr = word.splice(1,1,'world');  
    console.log(word);      //["c", "world", "d"]  
    console.log(newArr);    //["hello"]  

小丑的帽子
146 声望2 粉丝

« 上一篇
git学习笔记
下一篇 »
vue3.0的变化