[js專題2]-----數組array

0、數組的方法大合集

含義 方法 返回值 改變原數組
刪除 pop() 刪除項 yes
刪除 shift() 刪除項 yes
截取 slice() 刪除項 no
刪除 splice() 新數組 yes
刪除 length / yes
添加 push() length yes
添加 unshift() length yes
添加 concat() 新數組 no
添加 splice() 刪除項 yes
添加 [...array,...array1] 新數組 no
添加 Array.prototype.push.apply(arr1,arr2) length yes
splice() 新數組 yes
排序 sort() 新數組 yes
反向 reverse() 新數組 yes
遞歸 reduce() 計算的值 no
遞歸 reduceRight() 計算的值 no
查位置 indexof() 位置 no
反向查位置 lastIndexOf() 位置 no
找到第一個符合的成員 find() 成員 no
找到第一個符合的位置 findIndex() 位置 no
包含值否 includes() boolean no
計算 map() 計算後 no
過濾 filter() 知足條件的 no
判斷都 every() boolean no
判斷有 some() boolean no
遍歷 forEach() return的值 no
string->arry split() array no
arry->string join() string no
arry->string toString() string no
arry->string toLocalString() string no
obj-->arry for ..in 循環賦值法 / /
obj-->arry Array.from() 新數組 /
number-->arry Array.of() 新數組 /
填充/替換 fill(值,start,end) 新數組 yes
鍵值對 entries() 鍵值對 no
建值 keys() 建值 no
建名 values() 建名 no
指定位置的成員複製到其餘位置 copyWithin(target,start,end) 新數組 yes

1、對數組的增 刪 改 查:

數組的增長node

array.push()   向數組末尾添加元素,返回的是添加後新數組的長度,原有數組改變
array.unshift()  向數組開頭添加元素,返回的是添加後新數組的長度,原有數組改變
array.splice(n,m,x)   從索引n開始刪除m個元素,而後插入元素x,把刪除的內容當作新數組返回,原有數組改變。做添加使用,將m設置爲0 便可。
array.concat(),拼接數組。返回拼接以後的數組,原數組不改變。
[...arr1, ...arr2, ...arr3] 解構數組,數組與數組的合併,返回合併的數組,原數組不改變。
Array.prototype.push.apply(arr1,arr2);----將arr2追加到arr1中,返回數組的長度,改變原數組。

clipboard.png

數組的刪除git

array.pop() 刪除數組的最後一項,返回的是刪除的那一項,原有數組改變
array.shift() 刪除數組的的第一項,返回的是刪除的那一項,原有數組改變
splice(n,m,x) 從索引n開始刪除m個元素,而後插入元素x,把刪除的內容當作新數組返回,原有數組改變。做刪除使用,x不傳入數據既可。
slice(n,m) 從索引n開始刪除m個元素,返回刪除項,原數組不變
length   減少數組的長度,實際是從數組尾部刪除元素,改變原數組。

es6

其實只有一種 splice(),但delete方法,我我的感受算修改不屬於刪除,詳情請見實例


indeOf()
lastIndexOf()
find()
findIndex()
includes()github

[1, 4, -5, 10].find((n) => n < 0)    // -5
[1, 4, -5, 10].findIndex((n) => n < 0) // 2
[1, 2, 3].includes(2)     // true

2、數組深淺拷貝

對象和數組的拷貝有兩種
淺拷貝即 拷貝了指針指向,當一個對象的值改變會影響另外一個對象的值。
深拷貝, 拷貝的是真正的值。2者相互獨立,互不干擾。
淺拷貝的方法4種方法
slice() concat() 賦值法 遍歷
注:concat 和 slice 對一維數組 能算是深拷貝;2維的 是淺拷貝數組

var  a= [1,2,3,4]
b= a.concat();
c=a.concat();
b[0] = 5;
c[0] = 6;
a // [1,2,3,4]
b // [5,2,3,4]
c // [6,2,3,4]
var  aa= [[1,1],[2,2],3,4]
bb= aa.concat();
cc=aa.concat();
bb[1][0] = 5;
cc[0] = 6;
aa // [[1,1],[5,2],3,4]
b // [[1,1],[5,2],3,4]
c // [6,[5,2],3,4]

var shallowCopy = function(obj) {app

// 只拷貝對象
if (typeof obj !== 'object') return;
// 根據obj的類型判斷是新建一個數組仍是對象
var newObj = obj instanceof Array ? [] : {};
// 遍歷obj,而且判斷是obj的屬性才拷貝
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        newObj[key] = obj[key];
    }
}
return newObj;

}
深拷貝的方法5種方法:
一維數組和對象的concat slice法 JSON.parse(JSON.stringify(arr)) 和遍歷法 解構賦值法
示例:(前3種畢竟簡單,這裏也不表述)
解構賦值法:const a1 = [1, 2]; const a2 = [...a1];或者const [...a2] = a1;dom

var deepCopy = function(obj) {ide

if (typeof obj !== 'object') return;
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    }
}
return newObj;

}函數

3、數組與字符串 對象的轉換

3.1字符串轉數組

**es5 split(',');
es6 擴展運算符**es5

let hh = 'fh,fed,fd';
hh.split(','); // [fh,fed,fd]
[...'hello']
 // [ "h", "e", "l", "l", "o" ]

3.2數組轉字符串

2.1 toString();
2.2 toLocaleString();
2.3 join(',')
2.4 遍歷,而後拼接法
![這裏寫圖片描述](http://img.blog.csdn.net/20180201154816999?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2F0YXJhMTEwOQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

3.3 相似數組對象轉數組

  • es5 Array.prototype.slice.call(obj) / [].slice.call(obj)
  • es6 Array.from(obj)

一組值轉爲數組

es6 Array.of(2,3,4); // [2,3,4]

4、數組去重

[...new Set(arr1)]
這裏寫圖片描述

5、 數組的5個迭代方法----在數組的每一項上運行函數

filter();---返回true項的數組
map();-----返回運算後的組成的新數組
every();--每一項都是true,則返回true
forEach();-----無返回值
some();----有一項返回true,則返回true

6、並歸方法

reduce();
Array的reduce()把一個函數做用在這個Array的[x1, x2, x3...]上,這個函數必須接收兩個參數,reduce()把結果繼續和序列的下一個元素作累積計算,
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x + y;
}); // 25

reduceRight();反向並歸

七 判斷數組

2-3種方法
`
var ss=[];
typeof ss; // object
ss instanceof Array; // true
Array.isArray(ss); // true;

`

八 將nodeList轉換成數組

(2方法)
var elements = document.querySelectorAll("p"); // NodeList var arrayElements = [].slice.call(elements); // Now the NodeList is an array var arrayElements = Array.from(elements); // This is another way of converting

九 數組元素的洗牌

var list = [1,2,3];
list.sort(function() { return Math.random() - 0.5 })); // [2,1,3]
上述的是 投機取巧的方式
真正的數組亂序,請見

function shuffle(a) {
  var length = a.length;
  var shuffled = Array(length);

  for (var index = 0, rand; index < length; index++) {
    rand = ~~(Math.random() * (index + 1));
    if (rand !== index) 
      shuffled[index] = shuffled[rand];
    shuffled[rand] = a[index];
  }

  return shuffled;
}
function shuffle(a) {
  var b = [];

  while (a.length) {
    var index = ~~(Math.random() * a.length);
    b.push(a[index]);
    a.splice(index, 1);
  }

  return b;
}

10.考題

1.

Array.isArray( Array.prototype )

 // true ;because:Array.prototype is an Array

2.

var a = [0];
if ([0]) {
  console.log(a == true);
} else {
  console.log("wut");
}
// false ;  
// because:[0] as a boolean is considered true. Alas, when using it in the comparisons it gets converted in a different way and all goes to hell.

3.

[]==[]

// false;because: == is the spawn of satan.

4.

var ary = Array(3);
ary[0]=2
ary.map(function(elem) { return '1'; });

// [1,empty*2]

5.

[1 < 2 < 3, 3 < 2 < 1]

// [true] // true <3 => 1<3  false < 1 => 0<1

6.

var a = [1, 2, 3],
    b = [1, 2, 3],
    c = [1, 2, 4]
a ==  b
a === b
a >   c
a <   c

// false false false true ;
// because:字面量相等的數組也不相等.  數組在比較大小的時候按照字典序比較
相關文章
相關標籤/搜索