Array数组对象

1,162 阅读14分钟

一、方法

1)concat() 连接数组 / 为数组添加元素

  • arrayObject.concat(arrayObject,arrayX,......,arrayX)
  • 返回新数组,不改变原数组
  • arrayX为数组,则返回[arrayObject,arrayX]
  • arrayX为数组对象,则返回添加了对象的新数组

2)join() 将数组转为字符串

  • arrayObject.join("separator")
  • 不改变原数组
  • 字符串以separator分割,不添加参数,默认以逗号分割

3)push() 向数组末尾添加元素

  • arrayObject.push(newelement1,newelement2,....,newelementX)
  • 改变原数组
  • 使用后会改变数组长度

4)pop() 获取数组最后一位

  • arrayObject.pop()
  • 改变原数组
  • 删除数组最后一个元素,数组长度-1,返回删除的元素的值
  • 如果数组已为空,则数组不改变,返回undefined

5)unshift() 向数组开头添加元素

  • arrayObject.unshift(newelement1,newelement2,....,newelementX)

  • 改变原数组,IE不支持

6)shift() 获取数组第一位

  • arrayObject.shift()
  • 改变原数组
  • 删除原数组第一位
  • 返回被删除的第一个元素的值

7)reverse() 颠倒顺序

  • arrayObject.reverse()
  • 改变原数组

8)sort() 排序

  • arrayObject.sort(function)
  • 改变原数组
  • function规定排序顺序,可选
  • 不指定function按照字符编码排序

9)slice() 截取

  • arrayObject.slice(start,end)
  • 不改变原数组
  • 返回有截取内容的子数组
  • start:从第几个开始,负值则从倒数第几个开始
  • end:到底几个结束,负值则至倒数第几个结束,不填写默认从start到数组结束
  • 正值时0位第一位,负值时-1为第一位
  • 前包后不包

10)splice() 删除 / 添加 / 替换

  • arrayObject.splice(index,howmany,item1,.....,itemX)
  • 改变原数组
  • index:必填,起始元素下标,可为负
  • howmany:必填,操作的元素数量,为0则不会删除
  • item:可选,添加的项目

11)toString() 数组转字符串

  • arrayObject.toString()
  • 将数组转为字符串,并返回字符串,元素以逗号分隔

12)toLocaleString() 转为本地字符串

  • arrayObject.toLocaleString()
  • 本地字符串,时间及数值类型为本地形式

13)valueOf()

  • arrayObject.valueOf()
  • 后台自动调用
  • 返回数组对象的原始值

14)toSource()

  • object.toSource()
  • 后台自动调用
  • 返回该对象的源代码

二、ES6新增

1)Array.from() 将对象转化为数组

  • 可转化的两类对象:类似数组的对象(array-like object)和可遍历(iterable)的对象
  • 类似数组的对象,本质特征只有一点,即必须有length属性
let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']

Array.from([1, 2, 3])
// [1, 2, 3]

Array.from({ length: 3 });
// [ undefined, undefined, undefined ]

  • 对于还没有部署该方法的浏览器,可以用Array.prototype.slice方法替代。
const toArray = (() =>
  Array.from ? Array.from : obj => [].slice.call(obj)
)();
  • 第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组
Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]
let spans = document.querySelectorAll('span.name');

// map()
let names1 = Array.prototype.map.call(spans, s => s.textContent);

// Array.from()
let names2 = Array.from(spans, s => s.textContent)
Array.from([1, , 2, , 3], (n) => n || 0)
// [1, 0, 2, 0, 3]
  • 如果map函数里面用到了this关键字,还可以传入Array.from的第三个参数,用来绑定this

类数组:blog.csdn.net/kinsxkins/a…

2)Array.of() 将数值转换为数组

  • 弥补数组构造函数Array()的因为参数个数的不同,会导致Array()的行为有差异的不足。
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

  • Array.of基本上可以用来替代Array()或new Array(),并且不存在由于参数不同而导致的重载。它的行为非常统一。
  • Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。
  • Array.of方法可以用下面的代码模拟实现
function ArrayOf(){
  return [].slice.call(arguments);
}

3)copyWithin() 将数组内部的数据复制到其他位置(覆盖原内容)

  • Array.prototype.copyWithin(target, start = 0, end = this.length)
  • target(必需):从该位置开始替换数据。如果为负值,表示倒数
  • start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算
  • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}

// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// 对于没有部署 TypedArray 的 copyWithin 方法的平台
// 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

4)find() 返回第一个符合条件的数组成员

  • 参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员
  • 如果没有符合条件的成员,则返回undefined
  • 可以发现NaN
[1, 4, -5, 10].find((n) => n < 0)
// -5
  • 第二个参数,用来绑定回调函数的this对象
function f(v){
 return v > this.age;
}
let person = {name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26
  • 回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组
[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10

5)findIndex() 返回第一个符合条件的位置

  • 如果所有成员都不符合条件,则返回-1
  • 可以发现NaN
[NaN].findIndex(y => Object.is(NaN, y))
// 0
  • 第二个参数,用来绑定回调函数的this对象
  • 回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组
[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

6)fill() 填充数组

  • fill方法用于空数组的初始化非常方便
['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]
  • 第二个和第三个参数,用于指定填充的起始位置和结束位置
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
//从 1 号位开始,向原数组填充 7,到 2 号位之前结束
  • 如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象
let arr = new Array(3).fill({name: "Mike"});
arr[0].name = "Ben";
arr
// [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

let arr = new Array(3).fill([]);
arr[0].push(5);
arr
// [[5], [5], [5]]

7)keys() 遍历后获取键名

  • 可以用for...of循环进行遍历
  • 返回一个遍历器对象
for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

8)values() 遍历后获取键值

  • 可以用for...of循环进行遍历
  • 返回一个遍历器对象
for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

9)entries() 遍历后获取键值和键名

  • 可以用for...of循环进行遍历
  • 返回一个遍历器对象
for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
  • 如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历。
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']

10)includes() 判断数组是否包含值

  • 返回一个布尔值,表示某个数组是否包含给定的值
[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true
  • 该方法的第二个参数表示搜索的起始位置,默认为0
  • 如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true

下面代码用来检查当前环境是否支持该方法,如果不支持,部署一个简易的替代版本

const contains = (() =>
  Array.prototype.includes
    ? (arr, value) => arr.includes(value)
    : (arr, value) => arr.some(el => el === value)
)();
contains(['foo', 'bar'], 'baz'); // => false

11)flat() 将嵌套的数组拉平

  • 默认拉平一层,需要拉平多层,可以添加参数
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
  • 不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]

  • 如果原数组有空位,flat()方法会跳过空位
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]

12)flatMap() 拉平遍历函数返回的数组

  • flatMap()方法对原数组的每个成员执行一个函数,然后对返回值组成的数组执行flat()方法
  • 返回一个新数组,不改变原数组
// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
  • flatMap()只能展开一层数组
// 相当于 [[[2]], [[4]], [[6]], [[8]]].flat()
[1, 2, 3, 4].flatMap(x => [[x * 2]])
// [[2], [4], [6], [8]]
  • 遍历函数,该函数可以接受三个参数,分别是当前数组成员、当前数组成员的位置(从零开始)、原数组
arr.flatMap(function callback(currentValue[, index[, array]]) {
  // ...
}[, thisArg])
  • flatMap()方法还可以有第二个参数,用来绑定遍历函数里面的this

12)... 拓展运算符 — 将数组转化为以逗号分隔的参数序列

  • 与函数结合
function f(v, w, x, y, z) { }
const args = [0, 1];
f(-1, ...args, 2, ...[3]);
function f(v, w, x, y, z) { }
const args = [0, 1];
f(-1, 0 , 1, 2, 3);
  • 放置表达式
const arr = [
  ...(x > 0 ? ['a'] : []),
  'b',
];
  • 如果扩展运算符后面是一个空数组,则不产生任何效果
  • 只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错
(...[1, 2])
// Uncaught SyntaxError: Unexpected number

console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number

console.log(...[1, 2])
// 1 2
  • 替代函数的apply方法
function f(x, y, z) {
}
var args = [0, 1, 2];
f.apply(null, args);

// ES6的写法
function f(x, y, z) {
}
let args = [0, 1, 2];
f(...args);
// ES5 的写法
Math.max.apply(null, [14, 3, 77])

// ES6 的写法
Math.max(...[14, 3, 77])

// 等同于
Math.max(14, 3, 77);
// ES5的 写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);

// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
// ES5
new (Date.bind.apply(Date, [null, 2015, 1, 1]))
// ES6
new Date(...[2015, 1, 1]);

拓展运算符的应用

  • 复制数组
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
  • 合并数组(浅拷贝)
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];

// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]

// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
  • 与解构赋值结合(只能放在最后一位)
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest  // [2, 3, 4, 5]

const [first, ...rest] = [];
first // undefined
rest  // []

const [first, ...rest] = ["foo"];
first  // "foo"
rest   // []
  • 将字符串转化为数组
[...'hello']
// [ "h", "e", "l", "l", "o" ]
  • 识别四字节的Unicode字符
'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3
  • 将遍历器(Iterator)接口的对象转为数组
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];

含有Iterator接口的对象(待补充):

  • Node.childNodesdocument.querySelectorAll返回的 NodeList对象
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
  • Map结构和set结构
let map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

let arr = [...map.keys()]; // [1, 2, 3]

map结构:www.cnblogs.com/sky90370025…

set结构:blog.csdn.net/qq_26834399…

  • Generator 函数
const go = function*(){
  yield 1;
  yield 2;
  yield 3;
};

[...go()] // [1, 2, 3]

参考:www.liaoxuefeng.com/wiki/102291…

14)数组的空位

  • 数组的空位指,数组的某一个位置没有任何值。比如,Array构造函数返回的数组都是空位
Array(3) // [, , ,]
  • 空位不是undefined,一个位置的值等于undefined,依然是有值的

  • ES5 对空位的处理

    forEach() , filter() , reduce() , every() 和some()都会跳过空位

    map()会跳过空位,但会保留这个值

    join()toString()会将空位视为undefined,而undefined和null会被处理成空字符串

    // forEach方法
    [,'a'].forEach((x,i) => console.log(i)); // 1
    
    // filter方法
    ['a',,'b'].filter(x => true) // ['a','b']
    
    // every方法
    [,'a'].every(x => x==='a') // true
    
    // reduce方法
    [1,,2].reduce((x,y) => x+y) // 3
    
    // some方法
    [,'a'].some(x => x !== 'a') // false
    
    // map方法
    [,'a'].map(x => 1) // [,1]
    
    // join方法
    [,'a',undefined,null].join('#') // "#a##"
    
    // toString方法
    [,'a',undefined,null].toString() // ",a,,"
    
    
  • ES6明确将空位转为undefined

    Array.from扩展运算符(...)entries()keys()values()find()findIndex() 会将数组的空位,转为undefined

    copyWithin()会连空位一起拷贝

    fill()会将空位视为正常的数组位置

    for...of循环也会遍历空位

    Array.from(['a',,'b'])
    // [ "a", undefined, "b" ]
    
    [...['a',,'b']]
    // [ "a", undefined, "b" ]
    
    [,'a','b',,].copyWithin(2,0) // [,"a",,"a"]
    
    new Array(3).fill('a') // ["a","a","a"]
    
    let arr = [, ,];
    for (let i of arr) {
    console.log(1);
    }
    // 1
    // 1
    
    // entries()
    [...[,'a'].entries()] // [[0,undefined], [1,"a"]]
    
    // keys()
    [...[,'a'].keys()] // [0,1]
    
    // values()
    [...[,'a'].values()] // [undefined,"a"]
    
    // find()
    [,'a'].find(x => true) // undefined
    
    // findIndex()
    [,'a'].findIndex(x => true) // 0
    

三、属性

1) constructor 返回类型

  • object.constructor
<script type="text/javascript">

var test=[1,2,3,4]

if (test.constructor==Array)
{
document.write("This is an Array");
}
This is an Array

2) length 数组长度

  • arrayObject.length

3) prototype 添加属性

  • object.prototype.name=value
<script type="text/javascript">

function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}

var bill=new employee("Bill Gates","Engineer",1985);

employee.prototype.salary=null;
bill.salary=20000;

document.write(bill.salary);

</script>
20000

四、遍历数组

1)forEach()

  • 循环数组
  • 不会改变元素
  • 不会返回新数组
  • 提供一个回调函数,可用于处理数组的每一个元素,默认没有返回值
  • 回调函数的参数,第一个是处于当前循环的元素,第二个是该元素下标,第三个是数组本身,三个参数均可选
    let arr = [1,2,3,4,5];
    let res = 0;
    arr.forEach(item =>){
      item>=3?res++:res
    });
    console.log(res)
    

2)map() ——返回新元素、新数组

  • 遍历数组
  • 对每个元素进行处理
  • 返回元素
  • 返回一个新数组
  • 数组元素的映射,它提供一个回调函数,参数依次为处于当前循环的元素该元素下标数组本身,三者均可选
  • 返回的新数组是原数组的元素执行了回调函数后返回的值
    let arr = [1,2,3,4,5];
    let res = arr.map((item,index)=>{
       return item*(index+1)
    });
    console.log(arr)
    console.log(res)
    //[1,2,3,4,5]
    //[1,4,9,16,25]
    

3)some() ——有一个满足条件,返回true

  • 遍历数组
  • 在回调函数里进行条件的判断,返回 true 或 false
  • 当有一个元素满足条件时就停止遍历并返回true
  • 当全部的元素都不满足要求时,返回false
  • 提供一个回调函数,参数依次为处于当前循环的元素、该元素下标、数组本身,三者均可选
    let arr = [1,2,3,4,5];
    let resSome = arr.some((item,index)=>{
       return item*>=100
    });
    console.log(resSome)
    //false
    

4)every() ——全部满足条件,返回false

  • 遍历数组
  • 在回调函数里进行条件的判断,返回 true 或 false
  • 当全部元素都满足时,返回true
  • 当有一个元素不满足条件时就停止遍历并返回false
    let arr = [1,2,3,4,5];
    let resEvery= arr.every((item,index)=>{
       return item*>=100
    });
    console.log(resEvery)
    //false
    

5) filter() ——结果为true返回新数组

  • 遍历数组,在回调函数里进行条件判断,当结果为true时,将该元素返回,组成一个新数组
  • 过滤,即对数组元素的一个条件筛选
  • 它提供一个回调函数,参数依次为处于当前循环的元素该元素下标数组本身,三者均可选 默认返回一个数组,原数组的元素执行了回调函数之后返回值若为true,则会将这个元素放入返回的数组中
    let arr = [1,2,3,4,5];
    let res = arr.filter((item,index)=>{
        return item * index>=3
    });
    console.log(arr)
    console.log(res)
    //[1,2,3,4,5]
    //[3,4,5]
    

6) reduce()

  • 数组的每一个元素都执行一次回调函数,并将上一次循环时回调函数的返回值作为下一次循环的初始值,最后将这个结果返回
  • 如果没有初始值,则reduce会将数组的第一个元素作为循环开始的初始值,第二个元素开始执行回调函数
  • reduce方法有两个参数,第一个参数是一个回调函数(必须),第二个参数是初始值(可选)
  • 回调函数有四个参数,依次为本轮循环的累计值、当前循环的元素(必须),该元素的下标(可选),数组本身(可选) *最常用、最简单的场景,是数组元素的累加、累乘。
    let arr = [1,2,3,4,5];
    let res = arr.reduce((val,item,index)=>{
        return val+item*index
    },10);
    console.log(res)
    //50
    //10+(0*1)+(1*2)+(2*3)+(3*4)+(4*5)
    

7)for of 方法

  • es6新增了interator接口的概念,目的是对于所有数据结构提供一种统一的访问机制,这种访问机制就是for of

  • let arr = [1,2,3,4,5];
    for(let value of arr){
        console.log(value)
    }
    //1
    //2
    //3
    //4
    //5
    
  • 如果想用for of的方法遍历数组,又想用Index,可以用for of遍历arr.entries()

     let arr = [1,2,3,4,5];
     for(let [value,index] of arr.entries()){
         console.log(value,index)
     }
     //0 1
     //1 2
     //2 3
     //3 4
     //4 5