Array + String

116 阅读7分钟

Array

// 1. Array.length    返回或设置一个数组中的元素个数。

// 2. Array.prototype.push()    将一个或多个元素添加到数组的末尾,并返回该数组的新长度。改变原数组。
{
    const animals = ['pigs', 'goats', 'sheep'];
    const count = animals.push('cows');
    console.log(count);     // 4
    console.log(animals);    // ["pigs", "goats", "sheep", "cows"]
    console.log('------------------------------------------------2');
}

// 3. Array.prototype.pop()    从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。改变原数组。

// 4. Array.prototype.unshift()    将一个或多个元素添加到数组的开头,并返回该数组的新长度。改变原数组。
{
    const array1 = [1, 2, 3];
    console.log(array1.unshift(4, 5));      // 5
    console.log(array1);        // [4, 5, 1, 2, 3]
    console.log('-------------------------------------------------4');
}

// 5. Array.prototype.shift()   从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。改变原数组。

// 6. Array.prototype.splice()    通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。改变原数组。
{
    const array4 = [22, 33, 99, 88, 77]
    array4.splice(2, 1, 55, 100)    //第一个参数:开始操作的位置;第二个参数:操作的个数;第三个参数及其后面参数:需要在其位置添加的值。如果只有第一个参数代表后面作删除处理。
    console.log(array4);   // [ 22, 33, 55, 100, 88, 77 ]
    console.log(array4.splice(array4.length - 1));   // [ 77 ]   只有一个参数就是从开始位置进行删除后面返回值是数组[]
    console.log(array4);
    console.log('---------------------------------------------------------6');
}

// 7. Array.prototype.reverse()    将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,改变原数组。
{
    const array3 = ['one', 'two', 'three'];
    console.log('array3:', array3);     // array3: [ 'one', 'two', 'three' ]
    console.log('------------------------------------------------------7');
}

// 8. Array.prototype.sort()    排序;用原地算法对数组的元素进行排序(数值并不是大小排序),并返回数组。改变原数组。默认排序顺序是在将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列时构建的
{
    const months = ['March', 'Jan', 'Feb', 'Dec'];
    months.sort();
    console.log(months);    // ["Dec", "Feb", "Jan", "March"]
    const array2 = [1, 30, 4, 21, 100000];
    array2.sort();
    console.log(array2);    // [1, 100000, 21, 30, 4]
    // 升序
    arr1 = [25, 15, 35, 100, 70, 95]
    console.log(arr1.sort((a, b) => {
        return a - b;
    }));    // [ 15, 25, 35, 70, 95, 100 ]
    // 降序
    arr2 = [25, 15, 35, 100, 70, 95]
    console.log(arr2.sort((a, b) => {
        return b - a;
    }));    // [ 100, 95, 70, 35, 25, 15 ]
    console.log('--------------------------------------------------8');
}

// 2-8 对数组进行操作都会改变原数组

// 9. Array.prototype.slice()    截取一段数组返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(左闭右开 “[)”)。原始数组不会被改变。
{
    const ary = [1,2,3,4,5];
    console.log(ary.slice(1,3));    // [2,3]
    console.log('------------------------------------------------9');
}

// 10. Array.prototype.concat()    用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
{
    const array1 = ['a', 'b', 'c'];
    const array2 = ['d', 'e', 'f'];
    const array3 = array1.concat(array2);
    console.log(array3);    // ["a", "b", "c", "d", "e", "f"]
    console.log('---------------------------------------------------------10');
}

// 11. Array.prototype.map()    数组映射;创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
{
    const array1 = [1, 4, 9, 16];
    const map1 = array1.map(index => index * 2);
    console.log(map1);    // [2, 8, 18, 32]
    console.log('--------------------------------------------------------11');
}

// 12. Array.prototype.forEach()    对数组的每个元素执行一次给定的函数。item表示回调函数正在处理的元素;index索引值;arr处理的数组;thisArg处理时可以绑定的this。
{
    const array1 = ['a', 10, 'c']
    array1.forEach((item, index, arr) => {
        console.log(item, index, arr);
    })
    console.log('-----------------------------------------------------------12');
}

// 13. Array.prototype.every()    测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。遇到第一个false就终止。
{
    const array1 = [1, 30, 39, 29, 10, 13];
    const res = array1.every(item => item < 40)
    console.log(res);
    console.log('------------------------------------------------------------13');
}

// 14. Array.prototype.some()    测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回一个布尔值。遇到第一个true就终止。
{
    const array1 = [1, 30, 39, 29, 10, 13];
    const res = array1.some(item => item > 38)
    console.log(res);
    console.log('-------------------------------------------------------------14');
}

// 15. Array.prototype.find()    返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
{
    const array1 = [5, 12, 8, 130, 44];
    console.log(array1.find(item => item > 10));    // 12
    console.log(array1.find(item => item > 130));   // undefined
    console.log('--------------------------------------------------------------15');
}


// 16. Array.prototype.findIndex()    返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
{
    const array1 = [5, 12, 8, 130, 44];
    console.log(array1.findIndex(item => item > 10));   // 3
    console.log(array1.findIndex(item => item > 130));    // -1
    console.log('---------------------------------------------------------16');
}

// 17. Array.prototype.findLast()    返回数组中满足提供的测试函数条件的最后一个元素的值。如果没有找到对应元素,则返回 undefined。
// {
//     const array = [5, 12, 50, 130, 44, 30, 70, 10];
//     console.log(array.findLast(item => item > 45));    // 130
//     console.log('---------------------------------------------------------17');
// }

// 18. Array.prototype.findLastIndex()    返回数组中满足提供的测试函数条件的最后一个元素的索引。若没有找到对应元素,则返回 -1。
// {
//     const array1 = [5, 12, 50, 130, 44];
//     const isLargeNumber = (element) => element > 45;
//     console.log(array1.findLastIndex(isLargeNumber));
//     // expected output: 3  (of element with value: 30)
//     console.log('---------------------------------------------------------18');
// }

// 19. Array.prototype.indexOf()    返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。第一个参数代表要查找的元素;第二个参数代表开始查找的位置。
{
    const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
    console.log(beasts.indexOf('bison'));    // 1
    // start from index 2
    console.log(beasts.indexOf('bison', 2));    // 4
    console.log(beasts.indexOf('giraffe'));     // -1
    console.log('-----------------------------------------------------------19');
}

// 20. Array.prototype.lastIndexOf()    返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。第一个参数代表要查找的元素;第二个参数代表开始逆向查找的位置。
{
    const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo', 'lyl', 'll'];
    console.log(animals.lastIndexOf('Dodo', 4));    // 3
    console.log(animals.lastIndexOf('Tiger'));      // 1
    console.log('-------------------------------------------------------20');
}

// 21. Array.prototype.includes()    用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。第一个参数代表要查找的元素;第二个参数代表开始查找的位置。
{
    const array1 = [1, 2, 3];
    console.log(array1.includes(2));    // true
    const pets = ['cat', 'dog', 'bat'];
    console.log(pets.includes('cat', 1));    // false
    console.log(pets.includes('at'));    // false
    console.log('----------------------------------------------------------21');
}

// 22. Array.prototype.fill()    用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引(左闭右开 " [ ) " )。第一个值是用来填充的值
{
    const array1 = [1, 2, 3, 4];
    console.log(array1.fill('a', 2, 4));   // [ 1, 2, 'a', 'a' ]
    // fill with 5 from position 1
    console.log(array1.fill(5, 1));    // [ 1, 5, 5, 5 ]
    console.log(array1.fill('a'));     // [ 'a', 'a', 'a', 'a' ]
    console.log('------------------------------------------------------------22');
}

// 23. Array.prototype.join()    将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。
// 如果数组只有一个项目,那么将返回该项目而不使用分隔符。数组元素默认用逗号(,)分隔。如果是空字符串 (""),则所有元素之间都没有任何字符。
{
    const elements = ['Fire', 'Air', 'Water'];
    console.log(elements.join());    // "Fire,Air,Water"
    console.log(elements.join(''));     // "FireAirWater"
    console.log(elements.join('-'));     // "Fire-Air-Water"
    //  如果一个元素为 undefined 或 null,它会被转换为空字符串。
    const array = [99, 22, 33, null, undefined]
    console.log(array.join('+'));    // "99+22+33++"
    console.log('-------------------------------------------------23');
}

// 24. Array.prototype.toString()    把数组转换为字符串。
{
    const array1 = [1, 2, 'a', '1a'];
    console.log(array1.toString());     // "1,2,a,1a"
    console.log([].toString());    // ""
    console.log([12].toString());    // "12"
    console.log('--------------------------------------------24');
}

String

// 1. 与数组相似
{
    let str = '1111122222';
    console.log(str.length);    //==>字符串长度  10
    console.log(str[0]);    //==>获取索引为零(第一个)字符  1
    console.log(str[str.length-1]);    //==>获取最后一个字符  2
    console.log(str[10000]);    //==>undefined不存在这个索引   undefined
    console.log('------------------------------------------1');
}

// 2. String.prototype.charAt()     从一个字符串中返回指定的字符。相比较str[索引] 的优点;charAt索引过大或过小时返回空字符串,str[索引]返回undefined
{
    const str="xuexi"
    console.log(str.charAt(0));    //"x"
    console.log(str[0]);     //"x"
    console.log(str.charAt(100));     //""
    console.log(str[100]);    //undefined
    console.log('--------------------------------------------2');
}

// 3. String.prototype.substring()    截取字符串;实现字符串的截取(在原来字符串中查找到自己想要的)。左闭右开 [)
{
    let str = 'haohaoxunxitiantianxiangshang'
    console.log(str.substring(3,6));    // 'hao'
    console.log(str.substring(3));    // 'haoxunxitiantianxiangshang'截取到末尾
    console.log(str.substring(3,10000));    // 'haoxunxitiantianxiangshang'截取到末尾(超过索引的也只截取到末尾)
    console.log('----------------------------------------------3');
}

// 4. String.prototype.slice()     截取字符串;提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。左闭右开 [)
{
    let str = 'langyiliang'
    console.log(str.slice(4,6));    // 'li' 
    console.log(str.slice(-5));    // 'liang'   
    console.log('-------------------------------------------------4');
}

// ********substring与slice的区别:substring不支持负数索引

// 5. String.prototype.toLocaleLowerCase()    返回调用字符串被转换为小写的格式。
{
    console.log('ALPHABET'.toLocaleLowerCase());     // 'alphabet'
    console.log('---------------------------------------------------5');
}

// 6. String.prototype.toLocaleUpperCase()    返回调用字符串被转换为大写的格式。

// 7. String.prototype.split()    把字符串按照指定的分隔符拆分成数组(和数组中的join对应)。
{
    const str = 'The quick brown fox jumps over the lazy dog';
    const words = str.split(' ');
    console.log(words);     // [
    //     'The',   'quick',
    //     'brown', 'fox',
    //     'jumps', 'over',
    //     'the',   'lazy',
    //     'dog' ]
    console.log(words[3]);    // "fox"
    const chars = str.split('');
    console.log(chars);     // [
    //     'T', 'h', 'e', ' ', 'q', 'u', 'i',
    //     'c', 'k', ' ', 'b', 'r', 'o', 'w',
    //     'n', ' ', 'f', 'o', 'x', ' ', 'j',
    //     'u', 'm', 'p', 's', ' ', 'o', 'v',
    //     'e', 'r', ' ', 't', 'h', 'e', ' ',
    //     'l', 'a', 'z', 'y', ' ', 'd', 'o',
    //     'g' ]
    console.log(chars[8]);    // "k"
    const strCopy = str.split();
    console.log(strCopy);    // ["The quick brown fox jumps over the lazy dog"]
    console.log('--------------------------------------7');

}

// 8. String.prototype.replace()    把指定的字符替换成别的字符   str.replace(regexp|substr, newSubStr|function)
{
    const sentence = "Hi my name is Dillion"
    const replaced1 = sentence.replace("Dillion", "JavaScript")
    console.log(replaced1)     // "Hi my name is JavaScript"
    const replaced2 = sentence.replace(/\s/g, "-")
    console.log(replaced2)     // "Hi-my-name-is-Dillion"
    console.log('-------------------------------------8');
}