美文网首页
Array的方法

Array的方法

作者: 闲人追风落水 | 来源:发表于2022-04-06 13:44 被阅读0次
image.png
      ###静态方法
        // 测试array的方法
        // 1.Array.from()  静态方法
        // Array.from() 方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
        console.log(Array.from('foo'));
        // expected output: Array ["f", "o", "o"]
        console.log(Array.from([1, 2, 3], x => x + x));
        // expected output: Array [2, 4, 6]
        // Array.from(arrayLike[, mapFn[, thisArg]])

        // 2.Array.isArray()  静态方法
        // Array.isArray() 用于确定传递的值是否是一个 Array。
        Array.isArray([1, 2, 3]);
        // true
        Array.isArray({
            foo: 123
        });
        // false
        Array.isArray("foobar");
        // false
        Array.isArray(undefined);
        // false

        // 3.Array.of()  静态方法
        // Array.of() 方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。
        Array.of(7); // [7]
        Array.of(1, 2, 3); // [1, 2, 3]

        Array(7); // [ , , , , , , ]
        Array(1, 2, 3); // [1, 2, 3]
        // 实例属性
        // 4.Array.length    实例属性
        const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];

        console.log(clothing.length);
        // expected output: 4


        // 实例方法
        // 5.Array.prototype.concat()
        const array1 = ['a', 'b', 'c'];
        const array2 = ['d', 'e', 'f'];
        const array3 = array1.concat(array2);

        console.log(array3);
        // expected output: Array ["a", "b", "c", "d", "e", "f"]

        // 6.Array.prototype.copyWithin()
        // copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
        let array10 = ['a', 'b', 'c', 'd', 'e'];

        // copy to index 0 the element at index 3
        console.log(array10.copyWithin(0, 3, 4));
        // expected output: Array ["d", "b", "c", "d", "e"]

        // copy to index 1 all elements from index 3 to the end
        console.log(array10.copyWithin(1, 3));
        // 少一位,第一个必定是复制到的位置,不能缺少,剩下一个表示复制开始的位置,省去了结束的位置
        // expected output: Array ["d", "d", "e", "d", "e"]

        // 7.Array.prototype.entries()
        // entries() 方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
        // Iterator 的作用有三个:
        // 一是为各种数据结构,提供一个统一的、简便的访问接口;
        // 二是使得数据结构的成员能够按某种次序排列;
        // 三是 ES6 创造了一种新的遍历命令for...of循环,Iterator 接口主要供for...of消费。
        const array7 = ['a', 'b', 'c'];

        const iterator1 = array7.entries();

        console.log(iterator1.next().value);
        // expected output: Array [0, "a"]

        console.log(iterator1.next().value);
        // expected output: Array [1, "b"]



        // 8.Array.prototype.every()
        // every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
        const isBelowThreshold = (currentValue) => currentValue < 40;
        const array8 = [1, 30, 39, 29, 10, 13];
        console.log(array8.every(isBelowThreshold));
        // expected output: true
        console.log(isBelowThreshold(50))
        //  false

        // 9.Array.prototype.fill()
        // fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
        const array9 = [1, 2, 3, 4];

        // fill with 0 from position 2 until position 4
        console.log(array9.fill(0, 2, 4));
        // expected output: [1, 2, 0, 0]

        // fill with 5 from position 1
        console.log(array9.fill(5, 1));
        // expected output: [1, 5, 5, 5]

        console.log(array9.fill(6));
        // expected output: [6, 6, 6, 6]

        // 10.Array.prototype.filter()
        // filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。 
        const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

        const result = words.filter(word => word.length > 6);

        console.log(result);
        // expected output: Array ["exuberant", "destruction", "present"]

        // 11.Array.prototype.find()
        // find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
        const array11 = [5, 12, 8, 130, 44];

        const found = array11.find(element => element > 10);

        console.log(found);
        // expected output: 12
        // 12.Array.prototype.findIndex()
        // findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
        const array12 = [5, 12, 8, 130, 44];

        const isLargeNumber = (element) => element > 13;

        console.log(array12.findIndex(isLargeNumber));
        // expected output: 3

        // 13.Array.prototype.flat()
        // flat() 方法会按照一个可指定的深度递归遍历数组,
//并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
        const arr13 = [0, 1, 2, [3, 4]];

        console.log(arr13.flat());
        // expected output: [0, 1, 2, 3, 4]

        const arr132 = [0, 1, 2, [
            [
                [3, 4]
            ]
        ]];

        console.log(arr132.flat(2));
        // expected output: [0, 1, 2, [3, 4]]

        // 14.Array.prototype.forEach()
        // forEach() 方法对数组的每个元素执行一次给定的函数。
        const array14 = ['a', 'b', 'c'];

        array14.forEach(element => console.log(element));
        // expected output: "a"
        // expected output: "b"
        // expected output: "c"



        // 15.Array.prototype.includes()
        // includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,
//如果包含则返回 true,否则返回 false。
        const array15 = [1, 2, 3];

        console.log(array15.includes(2));
        // expected output: true

        const pets = ['cat', 'dog', 'bat'];

        console.log(pets.includes('cat'));
        // expected output: true

        console.log(pets.includes('at'));
        // expected output: false

        // 16.Array.prototype.indexOf()
        // indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
        const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

        console.log(beasts.indexOf('bison'));
        // expected output: 1

        // start from index 2
        console.log(beasts.indexOf('bison', 2));
        // expected output: 4

        console.log(beasts.indexOf('giraffe'));
        // expected output: -1

        // 17.Array.prototype.join()
        // join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符
       //串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。
        const elements = ['Fire', 'Air', 'Water'];

        console.log(elements.join());
        // expected output: "Fire,Air,Water"

        console.log(elements.join(''));
        // expected output: "FireAirWater"

        console.log(elements.join('-'));
        // expected output: "Fire-Air-Water"
        // 18.Array.prototype.keys()
        // keys() 方法返回一个包含数组中每个索引键的Array Iterator对象。
        const array18 = ['a', 'b', 'c'];
        const iterator = array18.keys();

        for (const key of iterator) {
            console.log(key);
        }

        // expected output: 0
        // expected output: 1
        // expected output: 2









        // Array.prototype.lastIndexOf()
        // lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索
        //引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。
        const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

        console.log(animals.lastIndexOf('Dodo'));
        // expected output: 3

        console.log(animals.lastIndexOf('Tiger'));
        // expected output: 1

        // Array.prototype.map()
        // map() 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
        const array19 = [1, 4, 9, 16];

        // pass a function to map
        const map1 = array19.map(x => x * 2);

        console.log(map1);
        // expected output: Array [2, 8, 18, 32]

        // Array.prototype.pop()
        // pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。
        const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

        console.log(plants.pop());
        // expected output: "tomato"

        console.log(plants);
        // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

        plants.pop();

        console.log(plants);
        // expected output: Array ["broccoli", "cauliflower", "cabbage"]

        // Array.prototype.push()
        // push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
        const animals1 = ['pigs', 'goats', 'sheep'];

        const count = animals1.push('cows');
        console.log(count);
        // expected output: 4
        console.log(animals1);
        // expected output: Array ["pigs", "goats", "sheep", "cows"]

        animals1.push('chickens', 'cats', 'dogs');
        console.log(animals1);
        // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

        // Array.prototype.reduce()
        // reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,
//每一次运行 reducer 会将先前元素的计算结果作为参数传入,
//最后将其结果汇总为单个返回值。 第一次执行回调函数时,
//不存在“上一次的计算结果”。 如果需要回调函数从数组索引为 0 的元素开始执行,
//则需要传递初始值。 否则,数组索引为 0 的元素将被作为初始值 initialValue,
//迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
        const array20 = [1, 2, 3, 4];

        // 0 + 1 + 2 + 3 + 4
        const initialValue = 0;
        const sumWithInitial = array20.reduce(
            (previousValue, currentValue) => previousValue + currentValue,
            initialValue
        );

        console.log(sumWithInitial);
        // expected output: 10

        // Array.prototype.reverse()
        // reverse() 方法将数组中元素的位置颠倒,并返回该数组。
//数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
        const array21 = ['one', 'two', 'three'];
        console.log('array1:', array21);
        // expected output: "array1:" Array ["one", "two", "three"]

        const reversed = array21.reverse();
        console.log('reversed:', reversed);
        // expected output: "reversed:" Array ["three", "two", "one"]

        // Careful: reverse is destructive -- it changes the original array.
        console.log('array21:', array21);
        // expected output: "array1:" Array ["three", "two", "one"]



        // Array.prototype.shift()
        // shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
        const array22 = [1, 2, 3];

        const firstElement = array22.shift();

        console.log(array22);
        // expected output: Array [2, 3]

        console.log(firstElement);
        // expected output: 1

        // Array.prototype.slice()
        // slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 
//决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。
        const animals3 = ['ant', 'bison', 'camel', 'duck', 'elephant'];

        console.log(animals3.slice(2));
        // expected output: Array ["camel", "duck", "elephant"]

        console.log(animals3.slice(2, 4));
        // expected output: Array ["camel", "duck"]

        console.log(animals3.slice(1, 5));
        // expected output: Array ["bison", "camel", "duck", "elephant"]

        console.log(animals3.slice(-2));
        // expected output: Array ["duck", "elephant"]

        console.log(animals3.slice(2, -1));
        // expected output: Array ["camel", "duck"]

        console.log(animals3.slice());
        // expected output: Array ["ant", "bison", "camel", "duck", "elephant"]


        // Array.prototype.some()
        // some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。
//它返回的是一个Boolean类型的值。
        const array23 = [1, 2, 3, 4, 5];

        // checks whether an element is even
        const even = (element) => element % 2 === 0;

        console.log(array23.some(even));
        // expected output: true

        // Array.prototype.sort()
        // sort() 方法用原地算法对数组的元素进行排序,并返回数组。
//默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的
        // 由于它取决于具体实现,因此无法保证排序的时间和空间复杂性。
        const months = ['March', 'Jan', 'Feb', 'Dec'];
        months.sort();
        console.log(months);
        // expected output: Array ["Dec", "Feb", "Jan", "March"]

        const array24 = [1, 30, 4, 21, 100000];
        array24.sort();
        console.log(array24);
        // expected output: Array [1, 100000, 21, 30, 4]
        // Array.prototype.splice()
        // splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,
//并以数组形式返回被修改的内容。此方法会改变原数组。
        const months1 = ['Jan', 'March', 'April', 'June'];
        months1.splice(1, 0, 'Feb');
        // inserts at index 1
        console.log(months1);
        // expected output: Array ["Jan", "Feb", "March", "April", "June"]

        months1.splice(4, 1, 'May');
        // replaces 1 element at index 4
        console.log(months1);
        // expected output: Array ["Jan", "Feb", "March", "April", "May"]

        // Array.prototype.toString()
        // toString() 返回一个字符串,表示指定的数组及其元素。

        const array25 = [1, 2, 'a', '1a'];

        console.log(array25.toString());
        // expected output: "1,2,a,1a"

        // Array.prototype.unshift()
        // unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度
//(该方法修改原有数组)。

        const array26 = [1, 2, 3];

        console.log(array26.unshift(4, 5));
        // expected output: 5

        console.log(array26);
        // expected output: Array [4, 5, 1, 2, 3]


        // Array.prototype.values()
        // values() 方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值
        const array27 = ['a', 'b', 'c'];
        const iterator2 = array27.values();
        console.log(iterator2.next())
        for (const value of iterator2) {
            console.log(value);
        }

        // expected output: "a"
        // expected output: "b"
        // expected output: "c"


相关文章

网友评论

      本文标题:Array的方法

      本文链接:https://www.haomeiwen.com/subject/yolrsrtx.html