[JavaScript] JavaScript 数组挖掘,不只是讲数组哟
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                [JavaScript] JavaScript 数组挖掘,不只是讲数组哟
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                課程來源:后盾人
數(shù)組引用類型分析
數(shù)組的定義
const array = new Array('hello', 'dust', 1, 2, 3, 4, 5)
console.log(array)
let arr = ['hello', 'dust', 1, 2, 3, 4, 5]
console.log(arr)
運行結果:
 
- 數(shù)組是引用類型的
 體現(xiàn):
let arr = ['hello', 'dust', 1, 2, 3, 4, 5]
console.log(arr)let hd = arr
hd[1] = 'hello,world'
console.log(arr)
console.log(hd)
- 引用類型傳的是"地址",而不是值。
- 這就像我買了一臺電腦,然后我把它“傳”給你的時候實際上是借給你。你如果把它弄壞了,那咱倆都用不了了。你如果在里面裝了個軟件,那咱倆都可以用這個軟件。
當我們隔空添加元素時,數(shù)組會自動補全中間的內容,用undefined填充
let lesson = ['class1', 'java']
lesson[5] = 'c++'
console.log(lesson)
console.log(lesson[2])
輸出結果:
 
多維數(shù)組
- a的情況:一般情況,一般我們在數(shù)組中都放對象為存儲形式。
- lesson的情況:在數(shù)組里套數(shù)組以實現(xiàn)多維數(shù)組。
let a = [{ name: 'java', number: 99 },{ name: 'c#', number: 666 },{ title: 'c#', bool: true },
]
console.log(a[1][1]) //undefined
console.log(a[1].name) //c#
console.log(a)
//   [
//     { name: 'java', number: 99 },
//     { name: 'c#', number: 666 },
//     { title: 'c#', bool: true }
//   ]let lesson = [['class1'], ['class2', 'java']]
console.log(lesson[1][1]) //java
輸出:
 
用Array.of為數(shù)組創(chuàng)建細節(jié)
- new Array(5)是創(chuàng)建一個長度為5的數(shù)組
- Array.of(5)是創(chuàng)建一個包含5的數(shù)組
let a = new Array(5)
console.log(a.length) //5
console.log(a[0]) //undefinedlet b = Array.of(5)
console.log(b.length) //1
console.log(b[0]) //5
運行結果:
 
類型檢測與轉換
數(shù)組轉換成字符串的兩種方式
- a.toString()返回一個字符串,把數(shù)組變成字符串。
- a.join('')返回一個字符串,用- join("這里的內容")來填充數(shù)組每一項之間的內容,不寫則為單純的連接。
- 與a.join('')相對的還有一個.split(" "),意思是將一個數(shù)組根據(jù)內容拆分。
- 描述起來還是不那么直觀,以下用一小段代碼演示
let a = [1, 3, 4]
console.log(typeof a)
b = a.join('lalala')
console.log(b)
console.log(b.split('lalala'))
運行結果:
 
let a = [1, 3, 4]
console.log(typeof a)
console.log(a.toString())
console.log(a)
console.log(a.join(''))
console.log(location.href + '?id=' + a.join(''))
運行結果:
 
querySelectorAll返回的也是數(shù)組
- 可以體驗一下如下的代碼:
- test4.js
let divs = document.querySelectorAll('div')console.log(Array.from(divs, function (i) {i.style.backgroundColor = 'lightgray'return i}),
)
- test.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><div class="div1">hello</div><p>emmmmm</p><div class="div2">dust</div><script src="./test4.js"></script></body>
</html>
運行結果:
 
- Array.from是一個迭代函數(shù),可以轉換數(shù)組,也可以對數(shù)組里的元素進行一些二次處理。
- 在此如果看不懂可以略過。
- 遍歷一個數(shù)組的方式還是有挺多的。
在一個數(shù)組后面加一個新的數(shù)組
- 在這里用到for-of語法,如果有不會的回去看JavaScript 運算符與流程控制
- 在文章中間偏后的位置有介紹for-of的使用哦
- 還要用到數(shù)組的.push()api,意思是往數(shù)組后添加一項,添加的就是括號內的內容。
- console.table(arr)的用途:看下面輸出的樣子
//展開語法真的好用啊
let arr = ['hello', 'dust']
let hd = ['js', 'css']
for (const value of hd) {arr.push(value)
}
console.log(arr);
console.table(arr)
運行結果:
兩個console里顯示樣式不同
 
解構賦值
- 展開語法真是太好用了
- ...表示展開
- 展開語法表示我們來接收這個變量,把多個元素賦值給一個變量。
//展開語法真的好用啊
let arr = ['hello', 'dust']
let hd = ['js', 'css']
arr = [...arr, ...hd]
console.log(arr)
運行結果:
 
配合reduce()使用解構賦值求和
 
let arr = ['hello', 'dust']
let hd = ['js', 'css']
function sum(...args) {return args.reduce((s, v) => {return (s += v)}, 0)
}
console.log(sum(1, 2, 4, 5))
運行結果:
 
解構賦值控制元素
- 寫一個點擊就隱藏的事件
- test6.js
const div = document.querySelectorAll('div')let q = [...div].map(function (i) {i.addEventListener('click', function () {this.classList.toggle('hide')})
})
- test.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><style>.hide {display: none;}</style><div class="div1">hello</div><p>emmmmm</p><div class="div2">dust</div><script src="./test6.js"></script></body>
</html>
運行結果:
 
 點擊div后隱藏
 
- 這里的q是什么類型的呢?把光標懸浮到q上方,看到q是void[]類型的。
其它解構賦值
- 比如這樣,也是一種解構賦值
let arr = ['dust', 20]
let [name, age] = arr
console.log(name, age)
運行結果:
 
- 字符串也可以被轉化成數(shù)組
console.log(...'hello')
let a = [...'hello']
console.log(a.length)
console.log(typeof a)
運行結果:
 
吸星大法
- name被吸走啦!
let [name, ...args] = ['dust', 'student', 20]
console.log(args)
運行結果:
 
多種添加元素的方式
- 首先我們定義兩個數(shù)組
let arr = ['dust', 'student', 20]
let lang = ['js', 'css']
- 直接添加
arr[arr.length] = 'hello1'
arr[arr.length] = 'hello2'
- 批量追加
arr = [...arr, ...lang]
- .push方法
- 在數(shù)組末尾添加一項
arr.push(...lang)
- 與.push()相對的.pop()操作
- 彈出數(shù)組的最后一項
arr.push(...lang)
console.log(arr)
let a = arr.pop()
console.log(a)
console.log(arr)
在數(shù)組中添加(修改)
- .fill()
let a = [1, 2, 3, 4]
a.fill('hhh', 1, 3)
console.log(a)
運行結果:
 
在數(shù)組中增刪
- slice截取
- 不改變原數(shù)組
let a = [1, 2, 3, 4]
//從1截到2,slice不改變原數(shù)組
console.log(a.slice(1, 2)) //[ 2 ]
//從2開始截
console.log(a.slice(2)) //[ 3, 4 ]
- splice在某一位置增或刪(刪就是不增)
- 會改變原數(shù)組
let a = [1, 2, 3, 4]//splice截幾個
console.log(a.splice(0, 3)) //[ 1, 2, 3 ]
這個時候a已經改變了,下面這段代碼要把上面這段注釋掉再運行。
let a = [1, 2, 3, 4]//splice刪除,增加操作
a.splice(1, 1)
console.log(a) //[ 1, 3, 4 ]
a.splice(1, 0, 'hello')
console.log(a) //[ 1, 'hello', 3, 4 ]
小函數(shù):移動數(shù)組里的一部分
let arr = [0, 1, 2, 3, 4, 5]
//移動數(shù)組里的一部分
function move(arr, from, to) {//聲明一個新數(shù)組,不要改變原數(shù)組const newArr = [...arr]let item = newArr.splice(from, 1)newArr.splice(to, 0, ...item)return newArr
}
let a = move(arr, 1, 3)
console.log(a)
運行結果:
 
清空數(shù)組的方式
- 以下幾種方式都可以清空數(shù)組
let a = [0, 1, 2, 3, 4, 5]
a = []
a.length = 0a.splice(0, a.length)while (a.pop()) {}
split和join的使用
 
- split:按什么拆分
- `join``:按什么合并
- 不改變原數(shù)組
let str = 'hello,dust'
console.log(str.split(','))
let hd = str.split(',') //[ 'hello', 'dust' ]
hd.join('-')
//不改變原數(shù)組
console.log(hd) //[ 'hello', 'dust' ]
console.log(hd.join('-')) //hello-dust
find和findIndex的使用
 
- (這兩個在對象中格外好用)
- find的使用
let a = [1, 2, 3, 4, 5]//find的使用
let res = a.find((item) => {return item == 2
})
console.log(res) //2
- find在對象中的使用
- 對象是引用類型,includes查找的是地址,所以不存在(includes括號里的內容相當于開辟了一塊新的地址)
- 用find+對象里的屬性就可以找到
let lessons = [{ name: 'js' }, { name: 'css' }, { name: 'mysql' }]
console.log(lessons.includes({ name: 'css' })) //false
//因為引用類型用的是地址
let res1 = lessons.find((item) => {return item.name == 'css'
})
console.log(res1) //{ name: 'css' }
- 注意下面這種是不行的:
let res1 = lessons.find((item) => {return item == { name: 'css' }
})
console.log(res1) //undefined
- findIndex在對象中的使用
- 可以找到你所找的這個對象的index值
let resIndex = lessons.findIndex((item) => {return item.name == 'css'
})
console.log(resIndex) //1
- 隨口一提:對象也是有長度(length屬性)的
let lessons = [{ name: 'js' }, { name: 'css' }, { name: 'mysql' }]
console.log(lessons.length) //2
自定義find函數(shù)
function find(array, callback) {for (const value of array) {if (callback(value)) return value}return undefined
}
let arr = [1, 2, 3, 4, 5]
console.log(find(arr, (item) => {return item == 2}),
) //2
運行結果:
 
原型鏈初體驗
說是初體驗,但我也不是第一次寫原型鏈了哈哈
說白了這里就是對于Array這個基本類型增加一個方法,自定義的!
//老師頭一次講原型啦!
Array.prototype.findValue = function (callback) {for (const value of this) {if (callback(value)) return value}return undefined
}
const res = arr.findValue((item) => {return item == 223
})
console.log(res) //undefined
運行結果:
 
神奇的排序
最近不知道為什么覺得什么都是神奇的……
- sort的原理:傳入一個函數(shù),看返回值,為非負就不交換,不然就交換。
- 下面是一個非常基礎的升序排序,如果要降序就是b-a(這個很好理解吧)
//排序
let arr = [1, 5, 3, 9, 7]
arr = arr.sort(function (a, b) {return a - b
})
console.log(arr) //[ 1, 3, 5, 7, 9 ]
輸出:
 
- 那么排序可不可以用在包含對象的數(shù)組中呢?
- 我們定義一個購物車,里面有一些商品和對應的價格,試一試。
let cart = [{ name: 'iphone', price: '12000' },{ name: 'imac', price: '18000' },{ name: 'ipad', price: '3200' },
]//注意傳進去的是item,但是return的一定是一個數(shù)值!
cart = cart.sort((a, b) => {return a.price - b.price
})
console.log(cart)
輸出:
 
用自己實現(xiàn)的方法寫出sort函數(shù)
有一說一,這一段沒什么實際意義,主要是看一下這個sort函數(shù)到底是個啥原理
當然,如果你理解什么是冒泡排序的話,那沒事了。
//自定義排序:冒泡算法
let arr = [1, 5, 3, 9, 7]
function sort(array, callback) {for (const n in array) {for (const m in array) {if (callback(array[n], array[m]) < 0) {const temp = array[n]array[n] = array[m]array[m] = temp}}}return array
}
console.log(sort(arr, (a, b) => {return a - b}),
) //[ 1, 3, 5, 7, 9 ]運行結果:
 
聽說文章一長,就沒人看到最后。
 更多內容,詳見下一期……
總結
以上是生活随笔為你收集整理的[JavaScript] JavaScript 数组挖掘,不只是讲数组哟的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: [C] 图的广度优先遍历
- 下一篇: 永源战隼3代350摩托车最高时速是多少?
