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"]
複製代碼
相關文章
相關標籤/搜索