JavaScript Array 属性、方法 (一)

JavaScript的 Array 对象是用于构造数组的全局对象javascript

属性

  • length

lengthArray的实例属性。 返回一个数组中的元素个数java

let numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.length);
// output: 6
复制代码

能够经过设置length的值来截断任何数组,也能够改变length的值来拓展数组web

let colors = ["red", "blue"];
console.log(colors.length)
// output: 2
colors.length = 1;
console.log(colors); 
// output[Array]: ["red"];

let clothing = ["shoes", "shirts"];
console.log(clothing.length)
// output: 2
clothing.length = 4;
console.log(clothing); 
// output[Array]: ["shoes", "shirts", empty x 2];
复制代码

方法

Array.from()

将一个类数组对象或者可遍历对象转换成一个真正的数组。数组

所谓类数组对象,最基本的要求就是具备length属性的对象app

将类数组对象转换为真正数组:

let arrayLike = {
  0: "allen",
  1: "50kg",
  2: "23",
  3: "165cm",
  length: 4 // 必须存在length属性
}
let arr = Array.from(arrayLike);
console.log(arr);
// output[Array]: ["allen", "50kg", "23", "165cm"]
复制代码
  • 若是去掉上述代码中的length属性呢?
let arrayLike = {
  0: "allen",
  1: "50kg",
  2: "23",
  3: "165cm"
}
let arr = Array.from(arrayLike);
console.log(arr);
// output[Array]: []
复制代码

结果是获得一个长度为0的数组函数

  • 若是修改上面数组 让其拥有length属性,可是属性名再也不是数字类型,而是字符串
let arrayLike = {
  "name": "allen",
  "weight": "50kg",
  "age": "23",
  "height": "165cm"
}
let arr = Array.from(arrayLike);
console.log(arr);
// output[Array]: [undefined, undefined, undefined, undefined]
复制代码

结果是获得的数组的长度为length, 元素都是 undefinedui

将一个类数组对象转换为一个真正的数组,必须具有如下条件spa

  1. 该类数组对象必须具备length属性,用于指定数组的长度。若是没有length属性,那么转换后的数组是一个空数组
  2. 类数组对象的属性名必须为数值型或字符串型的数字

将Set结构的数据转换为真正的数组

let arr = [10, 20, 30, 40, 40, 50]
let set = new Set(arr)
console.log(Array.from(set));
// output[Array]: [10, 20, 30, 40, 50]
复制代码

Array.from 还能够接受第二个参数,做用相似于数组的map方法,用来对每一个元素进行处理,将处理后的值放入返回的数组

let arr = [10, 20, 30, 40, 40, 50]
let set = new Set(arr)
console.log(Array.from(set, item => item*2));
// output[Array]: [20, 40, 60, 80, 100]
复制代码

Map 生成数组

const map = new Map([[1, 2], [2, 4], [4, 8]]);
console.log(Array.from(map));
//output[Array]: [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
console.log(Array.from(mapper.values()));
//output[Array]: ['a', 'b'];

console.log(Array.from(mapper.keys()));
// output[Array]: ['1', '2'];
复制代码

从类数组对象arguments生成数组

function fn() {
	return Array.from(arguments);
}
console.log(fn(1, 2, 3));
// output[Array]: [1, 2, 3];
复制代码

数组去重

function combine(){ 
  let arr = [].concat.apply([], arguments); // 没有去重复的新数组 
  return Array.from(new Set(arr));
} 
let m = [1, 2, 2],
    n = [2, 3, 3]; 
console.log(combine(m,n));
// output[Array]: [1, 2, 3];
复制代码

更多示例请查看 MDN web docprototype

Array.isArray()用于判断传递的值是不是一个Array(数组)

console.log(Array.isArray([1, 2, 3]))
// output: true
console.log(Array.isArray({foo: 123})); 
// output: false
console.log(Array.isArray("foobar"));   
// output: false
console.log(Array.isArray(undefined));  
// output: false
复制代码

当检测Array实例时, Array.isArray 优于 instanceof,由于Array.isArray能检测iframescode

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3);
console.log(arr);
// output[Array]: [1, 2, 3]
console.log(Array.isArray(arr));
// output: true
console.log(arr instanceof Array);
// output: false
复制代码

Array.of()

建立一个具备可变数量参数的新数组实例,而不考虑参数的数量或类型

console.log(Array.of(7));
// output[Array]: [7]
console.log(Array.of(1, 2, 3));
// output[Array]: [1, 2, 3]
console.log(Array(7))
// output[Array]: [empty x 7] ([ , , , , , , ]) 7个empty数组
console.log(Array(1, 2, 3))
// output[Array]: [1, 2, 3]
复制代码

Array.of()Array 构造函数之间的区别在于处理整数参数:Array.of(7) 建立一个具备单个元素 7 的数组,而 Array(7) 建立一个长度为7的空数组(**注意:**这是指一个有7个空位(empty)的数组,而不是由7个undefined组成的数组)。

Array.of()兼容旧环境

if (!Array.of) {
  Array.of = function() {
    return Array.prototype.slice.call(arguments);
  };
}
复制代码

concat()

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

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

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

// 拼接多个
const array3 = ['a', 'b', 'c'];
const array4 = ['d', 'e', 'f'];
const array5 = [1, 2, 3];

console.log(array3.concat(array4, array5));
// output[Array]: ["a", "b", "c", "d", "e", "f", 1, 2, 3]

复制代码

copyWithin()

方法浅复制数组的一部分到同一数组中的另外一个位置,并返回它,不会改变原数组的长度

arr.copyWithin(target[, start[, end]])
复制代码
  • target

目标索引位置(复制序列到该位置, 若是是负数,target 将从末尾开始计算。)

若是 target 大于等于 arr.length,将会不发生拷贝。若是 targetstart 以后,复制的序列将被修改以符合 arr.length

  • start

0 为基底的索引,开始复制元素的起始位置。若是是负数,start 将从末尾开始计算。

若是 start 被忽略,copyWithin 将会从0开始复制。

  • end

0 为基底的索引,开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。若是是负数, end 将从末尾开始计算。

若是 end 被忽略,copyWithin 方法将会一直复制至数组结尾(默认为 arr.length

let array1 = ['a', 'b', 'c', 'd', 'e'];
console.log(array1.copyWithin(0, 3, 4)); // 复制array1中索引为3到索引为4的元素到索引为0位置(包含3 不包含4)
//output[Array]: ["d", "e", "c", "d", "e"]

let array2 = ['a', 'b', 'c', 'd', 'e'];
console.log(array2.copyWithin(0, 3, 5)); // 复制array2中索引为3到索引为5的元素到索引为0位置(包含3 不包含5)
//output[Array]: ["d", "e", "c", "d", "e"]

let array3 = ['a', 'b', 'c', 'd', 'e'];
console.log(array3.copyWithin(0, 3)); // 复制array3中索引为3的元素到索引为0位置
//output[Array]: ["d", "e", "c", "d", "e"]
复制代码

MDN web doc 例子

let numbers = [1, 2, 3, 4, 5];

numbers.copyWithin(-2);
// [1, 2, 3, 1, 2]

numbers.copyWithin(0, 3);
// [4, 5, 3, 4, 5]

numbers.copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]

numbers.copyWithin(-2, -3, -1);
// [1, 2, 3, 3, 4]

[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}

// ES2015 Typed Arrays are subclasses of Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// On platforms that are not yet ES2015 compliant: 
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]
复制代码

entries()

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

Array Iterator是对象,它的原型(__proto__:Array Iterator)上有一个next方法,可用用于遍历迭代器取得原数组的[key,value]

  • Array Iterator数组迭代对象
let arr = ["a", "b", "c"];
let iterator = arr.entries();
console.log(iterator);
/*Array Iterator {} __proto__:Array Iterator next:ƒ next() Symbol(Symbol.toStringTag):"Array Iterator" __proto__:Object */
复制代码
  • iterator.next()
let arr = ["a", "b", "c"]; 
let iterator = arr.entries();
console.log(iterator.next());

/*{value: Array(2), done: false} done:false value:(2) [0, "a"] __proto__: Object */
// iterator.next()返回一个对象,对于有元素的数组,
// 是next{ value: Array(2), done: false };
// next.done 用于指示迭代器是否完成:在每次迭代时进行更新并且都是false,
// 直到迭代器结束done才是true。
// next.value是一个["key","value"]的数组,是返回的迭代器中的元素值
复制代码
  • iterator.next()方法运行
let arr = ["a", "b", "c"];
let iter = arr.entries();
let a = [];

// for(var i=0; i< arr.length; i++){ // 实际使用的是这个 
for(let i=0; i< arr.length+1; i++){    // 注意,是length+1,比数组的长度大
    let tem = iter.next();             // 每次迭代时更新next
    console.log(tem.done);             // 这里能够看到更新后的done都是false
    if(tem.done !== true){             // 遍历迭代器结束done才是true
        console.log(tem.value);
        a[i]=tem.value;
    }
}
    
console.log(a);                         // 遍历完毕,输出next.value的数组
复制代码
  • 二维数组按行排序
function sortArr(arr) {
    let goNext = true;
    let entries = arr.entries();
    while (goNext) {
        let result = entries.next();
        if (result.done !== true) {
            result.value[1].sort((a, b) => a - b);
            goNext = true;
        } else {
            goNext = false;
        }
    }
    return arr;
}

let arr = [[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]];
sortArr(arr);

/*(4) [Array(2), Array(5), Array(5), Array(4)] 0:(2) [1, 34] 1:(5) [2, 3, 44, 234, 456] 2:(5) [1, 4, 5, 6, 4567] 3:(4) [1, 23, 34, 78] length:4 __proto__:Array(0) */
复制代码
  • 使用for…of 循环
var arr = ["a", "b", "c"];
var iterator = arr.entries();
// output: undefined
for (let e of iterator) {
    console.log(e);
}
// output: [0, "a"] 
// output: [1, "b"] 
// output: [2, "c"]
复制代码
相关文章
相关标签/搜索