javascript 中Array一些高效的操作方法

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.isArray()

用于确定传递的值是否是一个 Array。

Array.isArray([1, 2, 3]);
// true
Array.isArray({foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false

Array.obsolete()

用于异步监视数组发生的变化

已被废弃 语法:Array.observe(arr, callback)

Array.of()

方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。

Array.of(7);       // [7]
Array.of(1, 2, 3); // [1, 2, 3]

Array(7);          // [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]
//es5
if (!Array.of) {
  Array.of = function() {
    return Array.prototype.slice.call(arguments);
  };
}

Array.concat()

方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

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

Array.copyWithin()

方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,而不修改其大小。

var array1 = [1, 2, 3, 4, 5];

// place at position 0 the element between position 3 and 4
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array [4, 2, 3, 4, 5]

// place at position 1 the elements after position 3
console.log(array1.copyWithin(1, 3));
// expected output: Array [4, 4, 5, 4, 5]

Array.entries()

方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。

var array1 = ['a', 'b', 'c'];

var iterator1 = array1.entries();

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

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

Array.every()

方法测试数组的所有元素是否都通过了指定函数的测试。

var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(x => x < 40 ));
//out true

Array.fill()

方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止

var array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

Array.filter()

方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

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

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

Array.find()

方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

var array1 = [5, 12, 8, 130, 44];

var found = array1.find( x => x > 10);

console.log(found);
// expected output: 12

Array.findIndex()

方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。

var array1 = [5, 12, 8, 130, 44];

var index = array1.findIndex( x => x > 10);

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

Array.flat()

方法会递归到指定深度将所有子数组连接,并返回一个新数组。

var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]

Array.flatMap()

方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 和 深度值1的 flat 几乎相同,但flatMap通常在合并成一种方法的效率稍微高一些。

var arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

Array.forEach()

方法对数组的每个元素执行一次提供的函数。

var array1 = ['a', 'b', 'c'];

array1.forEach((value,index,arr) => console.log(value));
// output 'a'
// output 'b'
// output 'c'

Array.includes(value,index)

方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

var array1 = [1, 2, 3];

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

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

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

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

Array.indexOf()

方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

/var 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

Array.join()

方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符

var elements = ['Fire', 'Wind', 'Rain'];

console.log(elements.join());
// expected output: Fire,Wind,Rain

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

console.log(elements.join('-'));
// expected output: Fire-Wind-Rain

//数组[1,2,3,3,4,5]求和
eval([1,2,3,3,4,5].join('+')) =18

Array.keys()

方法返回一个新的Array迭代器,它包含数组中每个索引的键。

var array1 = ['a', 'b', 'c'];
var iterator = array1.keys(); 

for (let key of iterator) {
  console.log(key); // expected output: 0 1 2
}

Array.lastIndexOf(item,index)

方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。

var animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

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

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

Array.map()

方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

var array1 = [1, 4, 9, 16];

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

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

Array.pop()

方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。

var 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.push()

方法将一个或多个元素添加到数组的末尾,并返回新数组的长度。

var animals = ['pigs', 'goats', 'sheep'];

console.log(animals.push('cows'));
// expected output: 4

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens');

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens"]

Array.reduce()

方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Array.reduceRight()

方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);

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

Array.reverse()

方法将数组中元素的位置颠倒。

var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']

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

/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']

Array.shift()

方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

var array1 = [1, 2, 3];

var firstElement = array1.shift();

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

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

Array.slice()

方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象。且原始数组不会被修改。

var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

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

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

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

Array.some()

方法测试数组中的某些元素是否通过由提供的函数实现的测试。

var array = [1, 2, 3, 4, 5];

var even = function(element) {
  // checks whether an element is even
  return element % 2 === 0;
};

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

Array.sort()

方法用原地算法对数组的元素进行排序,并返回数组。排序不一定是稳定的。默认排序顺序是根据字符串Unicode码点。

var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21];
array1.sort();
console.log(array1);
// expected output: Array [1, 21, 30, 4]

Array.splice()

方法通过删除现有元素和/或添加新元素来更改一个数组的内容。

var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// 增
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// 改
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
// 删
months.splice(4, 1);
console.log(months);
//output: ["Jan", "Feb", "March", "April"]

Array.toLocaleString()

返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。

var array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
var localeString = array1.toLocaleString('en', {timeZone: "UTC"});

console.log(localeString);
// expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
var prices = ['¥7', 500, 8123, 12];
prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });

// "¥7,¥500,¥8,123,¥12"

Array.toSource()

返回一个字符串,代表该数组的源代码.

该特性是非标准的,请尽量不要在生产环境中使用它!

var alpha = new Array("a", "b", "c");

alpha.toSource();   //返回["a", "b", "c"]

Array.toString()

返回一个字符串,表示指定的数组及其元素。

var array1 = [1, 2, 'a', '1a'];

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

Array.unshift()

方法将一个或多个元素添加到数组的开头,并返回新数组的长度。

var array1 = [1, 2, 3];

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

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

Array.values()

方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值

const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
  console.log(value);
  // expected output: "a" "b" "c"
}

原文地址:https://www.cnblogs.com/chuchur/p/10462285.html

时间: 2024-08-04 17:00:01

javascript 中Array一些高效的操作方法的相关文章

javascript 中Object一些高效的操作方法

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象. const object1 = { a: 1, b: 2, c: 3 }; const object2 = Object.assign({c: 4, d: 5}, object1); console.log(object2) // { a: 1, b: 2, c: 3 ,c: 4, d: 5 } Object.create() 方法创建一个新对象,使用现有的对象来提供新创建的对象的_

JavaScript中的常用的数组操作方法

JavaScript中的常用的数组操作方法 一.concat() concat() 方法用于连接两个或多个数组.该方法不会改变现有的数组,仅会返回被连接数组的一个副本. var arr1 = [1,2,3]; var arr2 = [4,5]; var arr3 = arr1.concat(arr2); console.log(arr1); //[1, 2, 3] console.log(arr3); //[1, 2, 3, 4, 5] 二.join() join() 方法用于把数组中的所有元素

Javascript 中 Array的 sort()和 compare()方法

Javascript 中 Array的 sort()方法其实是把要排序的内容转化为string(调用 toString()), 然后按照字符串的第一位 ascii 码先后顺序进行比较,不是数字. 我们看看官方是怎么说的: arrayobj.sort(sortfunction) 参数 arrayObj 必选项.任意 Array 对象. sortFunction 可选项.是用来确定元素顺序的函数的名称.如果这个参数被省略,那么元素将按照 ASCII 字符顺序进行升序排列. 说明 sort 方法将 A

JavaScript 中Array数组的几个内置函数

本文章内容均参考<JavaScript高级程序设计第三版> 今天在看JavaScript书籍的时候,看到之前没有了解过的JavaScript中Array的几个内置函数对象,为了之后再开发工作中能方便查询,故编写此随笔.直接贴代码, function arrayEffect(){ var numbers = [1,2,3,4,5,6,7,8,9,10]; //------------------------------------ 支持浏览器版本 IE9+,Firfox 2+ ,Safair 3

Javascript中Array的使用

JavaScript中的Array对象就是数组,首先是一个动态数组,而且是一个像C#.Java中“数组.List.HashMap/Dictionary”等的超强综合体. Array数组 使用方式: 例1: var citys = new Array();//创建数组对象,无需初始化长度,动态         citys[0] = '上海';         citys[1] ='北京';         citys[2] = '深圳'; for(var i=0; i< citys.length;

JavaScript中Array类型方法总结

Array类型是ECMAScript中最常用的类型之一,ECMAScript中的数组与其他多数语言中的数组有着相当大的区别.ECMAScript数组的每一项可以保存任何类型的数据.这里总结了数组类型的大多数方法,方便以后查找使用. 一.创建数组的基本方式 创建数据的基本方式有两种: 1.使用Array构造函数 var colors=new Array();var colors=new Array(20); //创建length值为20的数组var colors=new Array("red&qu

Javascript中Array.prototype.map()详解

map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数.callback 每次执行后的返回值组合起来形成一个新数组. callback 函数只会在有值的索引上被调用:那些从来没被赋过值或者使用 delete 删除的索引则不会被调用. 在我们日常开发中,操作和转换数组是一件很常见的操作,下面我们来看一个实例: 复制代码代码如下: var desColors = [],    srcColors = [        {r: 255, g: 255, b: 255 }, // W

JavaScript中Array数组的方法

查找: indexOf.lastIndexOf 迭代:every.filter.forEach.map.somereduce.reduceRight 用法: 1 /* 2 1 查找方法: 3 * arr.indexOf( value ) 4 * 一个参数 返回value所在数组的位置下标 5 * 找不到的时候返回-1 6 * 7 * arr.indexOf( start , value ) 8 * 从start开始查找value 返回下标 9 * 找不到的时候返回-1 10 * 11 * arr

javascript中 Array.prototype.slice的用法.

首先看到 www.w3school.cn上的解释:http://www.w3school.com.cn/jsref/jsref_slice_array.asp 定义和用法 slice() 方法可从已有的数组中返回选定的元素. 语法 arrayObject.slice(start,end) 参数 描述 start 必需.规定从何处开始选取.如果是负数,那么它规定从数组尾部开始算起的位置.也就是说,-1 指最后一个元素,-2 指倒数第二个元素,以此类推. end 可选.规定从何处结束选取.该参数是数