javascript
JS基础之数组--概述、创建数组的几种方式、数组的特点、数组的常用方法、数组的解构赋值、数组高级API
一、概述
- 描述:數(shù)組(array)是按照一定順序排列的一組值,每個值都擁有自己的編號,編號從0開始。整個數(shù)組用方括號來表示。
- 語法:var arr=[item1,item2,item3…]
1.1 注意
- 數(shù)組是按照一定順序排列的一組值,順序體現(xiàn)在下標,下標是從0開始- 和其他編程語言不同,如果數(shù)組對應(yīng)的索引中沒有存儲數(shù)據(jù),默認存儲的就是undefined- javascript中訪問了數(shù)組中不存在的索引不會報錯,會返回undefined- 當(dāng)javascript中數(shù)組的存儲空間不夠時數(shù)組會自動擴容- 數(shù)組在分配存儲空間的時候不一定是連續(xù)的;在瀏覽器中各大瀏覽器也對數(shù)組分配存儲空間進行了優(yōu)化,如果是相同類型數(shù)據(jù)則盡量分配連續(xù)的存儲空間,反之不會 - 數(shù)組元素:數(shù)組中的每一個值稱為數(shù)組元素,數(shù)組元素可以是**任意類型** <script>var str = 'hello world! goodbye world!';var result = str.split('o');console.log(result); // ["hell", " w", "rld! g", "", "dbye w", "rld!"] </script>二、創(chuàng)建數(shù)組的幾種方式
<script>//1var array = [];array[0] = "我";array[1] = "愛";array[2] = "生";array[3] = "活";alert(array);//2var array = ["我", "愛", "祖", "國"]; //定義數(shù)組并初始化console.log(array[0]); //通過索引值獲取數(shù)組的長度console.log(array[2]);console.log(array[3]);alert(array);//通過索引給元素賦值array[2] = "文";array[3] = "學(xué)";alert(array);//3var array1 = new Array(); //定義了一個空數(shù)組var array2 = new Array(5);var array3 = new Array("關(guān)曉彤", "趙麗穎", "張子楓");</script>三、數(shù)組的特點和遍歷
3.1 數(shù)組的本質(zhì)
- 描述:本質(zhì)上,數(shù)組是對象類型的一種特殊表現(xiàn)形式。
3.2 如何往數(shù)組中存儲數(shù)據(jù)?
變量名稱[索引號] = 需要存儲的數(shù)據(jù);
3.3 如何從數(shù)組中獲取存儲的數(shù)據(jù)?
變量名稱[索引號]
let arr = [1,2,3];console.log(arr[1]);3.4 注意點
- 和其它編程語言不同, 如果數(shù)組對應(yīng)的索引中沒有存儲數(shù)據(jù), 默認存儲的就是undefined
- JavaScript中訪問了數(shù)組中不存在的索引不會報錯, 會返回undefined
- 當(dāng)JavaScript中數(shù)組的存儲空間不夠時數(shù)組會自動擴容
- JavaScript的數(shù)組可以存儲不同類型數(shù)據(jù)
- JavaScript中數(shù)組分配的存儲空間不一定是連續(xù)的
- JavaScript數(shù)組是采用"哈希映射"方式分配存儲空間
- 什么是哈希映射? 好比字典可以通過偏旁部首找到對應(yīng)漢字, 我們可以通過索引找到對應(yīng)空間
- 在瀏覽器中各大瀏覽器也對數(shù)組分配存儲空間進行了優(yōu)化
- 如果存儲的都是相同類型的數(shù)據(jù), 那么會盡量分配連續(xù)的存儲空間
- 如果存儲的不是相同的數(shù)據(jù)類型, 那么就不會分配連續(xù)的存儲空間
3.5 數(shù)組的長度
- 描述:數(shù)組的長度實際是數(shù)組中元素的個數(shù)
- 語法:arr.length
- 因為數(shù)組中可以存儲任意類型的元素,因此數(shù)組在內(nèi)存中的存儲位置是不連續(xù)的,但是數(shù)組的下標是連續(xù)的
- length是一個可寫屬性
- 如果設(shè)置length的長度小于數(shù)組本身,那么多余元素舍去
- 如果設(shè)置length的長度大于數(shù)組本身,那么缺少的元素空位補齊
- 如果設(shè)置length的長度是不合法的值,那么會報 Invalid array length 錯誤
3.6 數(shù)組的遍歷
數(shù)組的遍歷就是依次取出數(shù)組中存儲的所有數(shù)據(jù)
- 描述:如果想要連續(xù)訪問數(shù)組中的每個元素,可以使用for in快速遍歷或者for循環(huán)遍歷依次取出數(shù)組中所有的元素。
3.7 數(shù)組的解構(gòu)賦值
解構(gòu)賦值是ES6中新增的一種賦值方式
- 數(shù)組解構(gòu)賦值的注意點
- 在數(shù)組的解構(gòu)賦值中, 等號左邊的格式必須和等號右邊的格式一模一樣, 才能完全解構(gòu)
- 在數(shù)組的解構(gòu)賦值中, 左邊的個數(shù)可以和右邊的個數(shù)不一樣
- 在數(shù)組的解構(gòu)賦值中, 右邊的個數(shù)可以和左邊的個數(shù)不一樣
- 在數(shù)組的解構(gòu)賦值中,如果右邊的個數(shù)和左邊的個數(shù)不一樣, 那么我們可以給左邊指定默認值
- 在數(shù)組的解構(gòu)賦值中, 如果左邊的個數(shù)和右邊的個數(shù)不一樣, 那么如果設(shè)置默認值會被覆蓋
- 在數(shù)組的解構(gòu)賦值中, 還可以使用ES6中新增的擴展運算符來打包剩余的數(shù)據(jù)
- 在數(shù)組的解構(gòu)賦值中, 如果使用了擴展運算符, 那么擴展運算符只能寫在最后
- ES6中新增的擴展運算符: …
3.8 數(shù)組的空位
- 描述:當(dāng)數(shù)組的某個位置是空元素,即兩個逗號之間沒有任何值,我們稱該數(shù)組存在空位(hole)
注意:
- 空位是計算數(shù)組長度的
- 空位表現(xiàn)為undefined
- 如果最后一個元素后面有逗號,這種情況并不會產(chǎn)生空位
3.9 在數(shù)組中添加新元素(增)
let arr=[1,2,3];arr[3] = 5;console.log(arr);// 增3.10 數(shù)組的’刪除’(刪)
- 描述:delete命令能夠刪除數(shù)組中的元素的值,從而形成空位。
- 但是delete命令并不會影響length的屬性。
- 語法:delete arr[下標]
- delete命令在使用的時候是根據(jù)數(shù)組下標來對指定數(shù)組的值進行刪除的
3.11 改變數(shù)組的值(改)
let arr=[1,2,3];arr[0] = 5;console.log(arr);// 改3.12 數(shù)組調(diào)用(查)
- 描述:數(shù)組的調(diào)用實際上指的是數(shù)組元素的調(diào)用。
- 數(shù)組元素通過【數(shù)組名+下標】的方式來進行訪問。
- 數(shù)組元素一次只能訪問一個,不能一次連續(xù)性地訪問多個;要想一次訪問多個那么則需運用for循環(huán)
- 語法:數(shù)組名[下標]
- 案例:
結(jié)果:
四、數(shù)組常用的方法
4.1 isArray()
- 描述:判斷變量是否是數(shù)組,如果是返回true,否則返回false
- 語法:Array.isArray();
4.2 valueOf()
- 描述:valueOf方法歸屬于Object對象類型
- 返回指定對象的原始值
- 在數(shù)組中作用是返回數(shù)組本身。
- 語法:arr.valueOf()
- javascript的許多內(nèi)置對象都重寫了該屬性,以實現(xiàn)更適合自身的功能需求。因此,不同對象類型的valueOf()方法的返回值類型均可能不同。
4.3 toString()
- 描述:能夠?qū)?shù)組轉(zhuǎn)換成字符串,默認是以逗號隔開
- 語法:arr.toString()
- 注意:不僅能夠合并數(shù)組元素,對布爾類型也能夠生成
4.4 join()
- 描述:join方法能夠以給定的參數(shù)做分隔符,將所有的數(shù)組元素組成一個字符串。
- 如果不提供參數(shù),默認使用逗號分隔,就是相當(dāng)于調(diào)用了 toString() 方法
- 語法:arr.join(‘分隔符’);
- join()方法不會對原數(shù)組造成影響
4.5 push()
- 描述:push方法用于在數(shù)組的 末端 添加一個或多個元素,并返回添加后的數(shù)組的長度。
- 語法:arr.push(item1,item2…);
注意:
- push方法會對原數(shù)組造成影響
- 可以根據(jù)需求來決定是否保存punsh方法結(jié)果
4.6 pop()
- 描述:pop方法用于刪除數(shù)組的最后一個元素,并以字符串的形式返回刪除的這個元素。
- poop()方法會對原數(shù)組造成影響
- 語法:arr.pop()
注意:
- pop方法沒有參數(shù)
- pop方法回對原數(shù)組造成影響
4.7 shift()
- 描述:shift方法用于刪除數(shù)組中的第一個元素,并返回刪除的這個元素
- shift()方法會對原數(shù)組造成影響
- 語法:arr.shift()
注意:
- 會對原數(shù)組造成影響
4.8 unshift()
- 描述:unshift方法用于在數(shù)組的第一個位置添加元素,并返回添加元素后新數(shù)組的長度。
- unshift()方法會對原數(shù)組造成影響
- 語法:arr.unshift(‘item1’,‘item2’…);
注意:
- 會對原數(shù)組造成影響
4.9 reverse()
- 描述:reverse方法能夠反序排列數(shù)組(反序排列)即數(shù)組反轉(zhuǎn)
- 語法:arr.reverse()
- reverse()方法會對原數(shù)組造成影響
注意:
- 會改變原數(shù)組的結(jié)構(gòu)
4.10 slice()
- 描述:slice方法作用是能夠根據(jù)指定的【起始點】和【結(jié)束點】來對數(shù)組進行截取,并生成一個新數(shù)組。
- 新數(shù)組的內(nèi)容是從起始點下標開始的元素到結(jié)束點下標的元素,但是不包括結(jié)束點下標的元素本身。
- 語法:arr.slice(fromIndex,toIndex);
注意:
- 前包后不包
- 不會對原數(shù)組結(jié)構(gòu)更改
4.11 splice()
- 描述:splice方法的作用是在指定下標處截取一定長度的元素,再插入一些新元素,并將刪除的元素構(gòu)成一個新數(shù)組返回。splice方法會改變原本數(shù)組。
-splice() 方法會對原數(shù)組造成影響 - 語法:arr.splice(fromIndex,removeCount,addItem1…)
注意:
- 會改變原數(shù)組的結(jié)構(gòu)
- 前兩個參數(shù)必須有,后面的是可選參數(shù)
4.12 sort()
- 描述:對數(shù)組進行排序,根據(jù)提供的排序規(guī)則,默認按照編碼方式排序
- 語法:arr.sort(排序的規(guī)則);
- soort()方法會對原數(shù)組造成影響
4.13 indexOf()
- 描述:indexOf方法能夠從前到后檢索數(shù)組,并返回元素在數(shù)組中的第一次出現(xiàn)的下標,如果沒有索引到則返回-1
- indexOf方法默認是從左至右的查找, 一旦找到就會立即停止查找
- 語法:arr.indexOf(item,fromIndex)
注意:
- 第一個參數(shù)是可選的,表示從第幾個下標開始向后查找
- 第二個參數(shù)可以是負值,表示從倒數(shù)第幾個下標開始向后查找
4.14 lastIndexOf()
- 描述:lastIndexOf方法能夠從后向前檢索數(shù)組,并返回元素在數(shù)組中的最后一次出現(xiàn)的下標,如果沒有索引到則返回-1
- lastIndexOf方法默認是從右至左的查找, 一旦找到就會立即停止查找
- 語法:arr.lastIndexOf(item,fromIndex)
4.15 concat()
數(shù)組拼接;不會修改原有的數(shù)組,會生成一個新數(shù)組返回
let arr1=[1,2,3,4,5];let arr2=[6,7];let arr3=[8,9];let arr=arr1.concat(arr2,arr3);//或:let arr=[...arr1,...arr2,...arr3];//console.log(arr);注意點:
數(shù)組不能夠使用加號進行拼接, 如果使用加號進行拼接會先轉(zhuǎn)換成字符串再拼接
在ES6中還有一種更簡單的方法可以去拼接數(shù)組:那就是利用擴展運算符 …
- 擴展運算符在解構(gòu)賦值中(等號的左邊)表示將剩余的數(shù)據(jù)打包成一個新的數(shù)組
- 擴展運算符在等號右邊, 那么表示將數(shù)組中所有的數(shù)據(jù)解開, 放到所在的位置
- 不會修改原有的數(shù)組, 會生成一個新的數(shù)組返回給我們
4.16 split()
根據(jù)指定格式切割字符串,轉(zhuǎn)換成一個數(shù)組后返回給我們
let arr1="1,2,3";let arr=arr1.split(",");4.17 toString()
將數(shù)組轉(zhuǎn)換成字符串
let arr1=[1,2,3,4,5];let arr=arr1.toString();console.log(arr);五、補充
5.1 forEach 快速遍歷
forEach函數(shù)的參數(shù)是一個匿名函數(shù),該匿名函數(shù)會在forEach函數(shù)的內(nèi)部調(diào)用,這種函數(shù)又被稱為回調(diào)函數(shù)。
傳入的回調(diào)函數(shù)要求有3個形參,分別是一次循環(huán)的數(shù)組的數(shù)據(jù)、正在循環(huán)的下標、數(shù)組本身
??????
5.2 for in 循環(huán)
在企業(yè)開發(fā)中不推薦使用forin循環(huán)來遍歷數(shù)組
let arr = [1, 3, 5, 7, 9];// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...infor (let key in arr) {// console.log(key);console.log(arr[key]);}注意點:
- 對象中的屬性是無序的
- forin循環(huán)是專門用于遍歷對象的, 但是對象的屬性是無序的, 所以forin循環(huán)就是專門用于遍歷無序的東西的, 所以不推薦使用forin循環(huán)來遍歷數(shù)組
5.3 for of循環(huán)
創(chuàng)建一個循環(huán)遍歷 可迭代對象 ,包括:內(nèi)置對象String、Array、arguments、NodeList、TypedArray、Map、Set和用戶定義的可迭代對象
該循環(huán)調(diào)用一個自定義迭代鉤子,其中包含要為對象的每個不同屬性的值執(zhí)行的語句
5.4 reduce()
對數(shù)組中的每個元素按序執(zhí)行一個由您提供的 reducer 函數(shù),每一次運行 reducer 會將先前元素的計算結(jié)果作為參數(shù)傳入,最后將其結(jié)果匯總為單個返回值
第一次執(zhí)行回調(diào)函數(shù)時,不存在“上一次的計算結(jié)果”
如果需要回調(diào)函數(shù)從數(shù)組索引為 0 的元素開始執(zhí)行,則需要傳遞初始值。否則,數(shù)組索引為 0 的元素將被作為初始值 initialValue,迭代器將從第二個元素開始執(zhí)行(索引為 1 而不是 0)
reducer 逐個遍歷數(shù)組元素,每一步都將當(dāng)前元素的值與上一步的計算結(jié)果相加(上一步的計算結(jié)果是當(dāng)前元素之前所有元素的總和)——直到?jīng)]有更多的元素被相加
? // Arrow function reduce((previousValue, currentValue) => { /* ... */ } ) reduce((previousValue, currentValue, currentIndex) => { /* ... */ } ) reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } ) reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)// Callback function reduce(callbackFn) reduce(callbackFn, initialValue)// Inline callback function reduce(function(previousValue, currentValue) { /* ... */ }) reduce(function(previousValue, currentValue, currentIndex) { /* ... */ }) reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }) reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)一個 “reducer” 函數(shù),包含四個參數(shù):
- previousValue:上一次調(diào)用 callbackFn 時的返回值。在第一次調(diào)用時,若指定了初始值 initialValue,其值則為 initialValue,否則為數(shù)組索引為 0 的元素 array[0]。
- currentValue:數(shù)組中正在處理的元素。在第一次調(diào)用時,若指定了初始值 initialValue,其值則為數(shù)組索引為 0 的元素 array[0],否則為 array[1]。
currentIndex:數(shù)組中正在處理的元素的索引。若指定了初始值 initialValue,則起始索引號為 0,否則從索引 1 起始 - array:用于遍歷的數(shù)組
- initialValue:作為第一次調(diào)用 callback 函數(shù)時參數(shù) previousValue 的值。若指定了初始值 initialValue,則 currentValue 則將使用數(shù)組第一個元素;否則 previousValue 將使用數(shù)組第一個元素,而 currentValue 將使用數(shù)組第二個元素
累加:
let arr = [1,4,5,6]; let sum = arr.reduce((x,y)=>{return x + y; }) console.log(sum); // 16數(shù)組去重:
const arr = [4,5,7,5,4,7,9]; const resultArr = arr.reduce((prev, current) => {prev.indexOf(current) == -1 && prev.push(current)return prev; }, []); console.log(resultArr); // [ 4, 5, 7, 9 ]二維數(shù)組降維:
const arr = [1,4,5,[7,8,9,23]]; // const resultArr = arr.reduce((x,y) => { // return x.concat(y) // }, []) const resultArr = arr.reduce((x,y) => x.concat(y) , []) console.log(resultArr); // [ 1, 4, 5, 7, 8, 9, 23 ]更多請參考官網(wǎng):reduce官網(wǎng)(MDN)
5.5 findIndex()
以前數(shù)組查找的方法:
- 從左往右查找, 找到返回索引, 找不到返回-1(.indexOf())
- 從右至左查找, 找到返回索引, 找不到返回-1(.lastIndexOf())
- 從左往右查找, 找到返回true, 找不到返回false(.includes())
定制版的indexOf, 找到返回索引, 找不到返回-1
let arr = [3, 2, 6, 7, 6];let index = arr.findIndex(function(currentValue, currentIndex, currentArray) {console.log(currentValue, currentIndex, currentArray);if (currentValue === 10) {return true;}});console.log(index);
更多詳情查看官方文檔:finedIndex
自定義findIndex
let arr = [3, 2, 6, 7, 6];// findIndex實現(xiàn)Array.prototype.myFindIndex = function(fn) {for (let i = 0; i < this.length; i++) {let result = fn(this[i], i, this);if (result) {return i;}}return -1;}let index = arr.myFindIndex(function(currentValue, currentIndex, currentArray) {// console.log(currentValue, currentIndex, currentArray);// if(currentValue === 6){if (currentValue === 10) {return true;}});console.log(index);5.6 find()
find方法如果找到了就返回找到的元素, 如果找不到就返回undefined
?let arr = [3, 2, 6, 7, 6];let value = arr.find(function(currentValue, currentIndex, currentArray) {console.log(currentValue, currentIndex, currentArray);// if(currentValue === 6){if (currentValue === 10) {return true;}});console.log(value);自定義find
let arr = [3, 2, 6, 7, 6];// find實現(xiàn)Array.prototype.myFind = function(fn) {for (let i = 0; i < this.length; i++) {let result = fn(this[i], i, this);if (result !== undefined) {return result;}}return undefined;}let index = arr.myFind(function(currentValue, currentIndex, currentArray) {// console.log(currentValue, currentIndex, currentArray);// if(currentValue === 6){if (currentValue === 10) {return true;}});console.log(index);5.7 map()
將滿足條件的元素映射到一個新的數(shù)組中
let arr = [1, 2, 3, 4, 5];let newArray = arr.map(function(currentValue, currentIndex, currentArray) {// console.log(currentValue, currentIndex, currentArray);if (currentValue % 2 === 0) {return currentValue;}});console.log(newArray); // [undefined, 2, undefined, 4, undefined]/*let newArray = arr.myMap(function(currentValue, currentIndex, currentArray) {// console.log(currentValue, currentIndex, currentArray);if (currentValue % 2 === 0) {return currentValue;}});Array.prototype.myMap = function(fn) {let newArray = new Array(this.length);newArray.fill(undefined);for (let i = 0; i < this.length; i++) {let result = fn(this[i], i, this);if (result !== undefined) {newArray[i] = result;}}return newArray;}*/5.8 every()
判斷數(shù)組中的數(shù)據(jù)是否全部滿足某個條件,當(dāng)所有數(shù)據(jù)都滿足某個條件時,返回true,否則返回false
?
測試一個數(shù)組內(nèi)的所有元素是否都能通過某個指定函數(shù)的測試。它返回一個布爾值
若收到一個空數(shù)組,此方法在一切情況下都會返回 true
語法:
arr.every(callback(element[, index[, array]])[, thisArg])
callback:用來測試每個元素的函數(shù),它可以接收三個參數(shù):
element:用于測試的當(dāng)前值。
index可選:用于測試的當(dāng)前值的索引。
array可選:調(diào)用 every 的當(dāng)前數(shù)組。
thisArg:執(zhí)行 callback 時使用的 this 值
every 方法為數(shù)組中的每個元素執(zhí)行一次 callback 函數(shù),直到它找到一個會使 callback 返回 falsy 的元素。如果發(fā)現(xiàn)了一個這樣的元素,every 方法將會立即返回 false。否則,callback 為每一個元素返回 true,every 就會返回 true。callback 只會為那些已經(jīng)被賦值的索引調(diào)用。不會為那些被刪除或從未被賦值的索引調(diào)用。
every 和數(shù)學(xué)中的"所有"類似,當(dāng)所有的元素都符合條件才會返回true。正因如此,若傳入一個空數(shù)組,無論如何都會返回 true
const isBelowThreshold = (currentValue) => currentValue < 40;const array1 = [1, 30, 39, 29, 10, 13];console.log(array1.every(isBelowThreshold));更多請參考官網(wǎng):every用法
5.9 some()
判斷數(shù)組中的數(shù)據(jù)是否至少有一個滿足某個條件,當(dāng)有一個數(shù)據(jù)滿足某個條件時,返回true,否則返回false
?
測試數(shù)組中是不是至少有1個元素通過了被提供的函數(shù)測試,接受三個參數(shù)
返回的是一個Boolean類型的值
語法:
arr.some(callback(element[, index[, array]])[, thisArg])
callback:用來測試每個元素的函數(shù),接受三個參數(shù):
element:數(shù)組中正在處理的元素。
index 可選:數(shù)組中正在處理的元素的索引值。
array可選
some()被調(diào)用的數(shù)組。
thisArg可選:執(zhí)行 callback 時使用的 this 值。
some() 為數(shù)組中的每一個元素執(zhí)行一次 callback 函數(shù),直到找到一個使得 callback 返回一個“真值”(即可轉(zhuǎn)換為布爾值 true 的值)。如果找到了這樣一個值,some() 將會立即返回 true。否則,some() 返回 false。callback 只會在那些”有值“的索引上被調(diào)用,不會在那些被刪除或從來未被賦值的索引上調(diào)用
some() 遍歷的元素的范圍在第一次調(diào)用 callback. 前就已經(jīng)確定了。在調(diào)用 some() 后被添加到數(shù)組中的值不會被 callback 訪問到。如果數(shù)組中存在且還未被訪問到的元素被 callback 改變了,則其傳遞給 callback 的值是 some() 訪問到它那一刻的值。已經(jīng)被刪除的元素不會被訪問到
const array = [1,2,3,4,5]; const even = (element) => element % 2 === 0; console.log(array.some(even));更多請參考官網(wǎng):some函數(shù)
5.10 filter()
將數(shù)組中滿足條件的數(shù)據(jù)保存在一個新數(shù)組中并返回
?let arr = [1, 2, 3, 4, 5];let newArray = arr.filter(function(currentValue, currentIndex, currentArray) {// console.log(currentValue, currentIndex, currentArray);if (currentValue % 2 === 0) {return true;}});console.log(newArray); // [2, 4]/*實現(xiàn)自定義的filter方法let arr = [1, 2, 3, 4, 5];// filter實現(xiàn)Array.prototype.myFilter = function(fn) {let newArray = [];for (let i = 0; i < this.length; i++) {let result = fn(this[i], i, this);if (result) {newArray.push(this[i]);}}return newArray;};let newArray = arr.myFilter(function(currentValue, currentIndex, currentArray) {// console.log(currentValue, currentIndex, currentArray);if (currentValue % 2 === 0) {return true;}});console.log(newArray); // [2, 4]*/?
5.11 刪除數(shù)組元素注意點
?let arr = [1, 2, 3, 4, 5];// 需求: 遍歷的同時刪除數(shù)組中所有元素// arr.splice(2, 1);// delete arr[2];console.log(arr);let len = arr.length; //length會變化,因此先保存//刪除完元素后,后面的元素會向前挪動,因此我們需要從后向前刪,這樣才能刪干凈for (let i = len - 1; i >= 0; i--) {arr.splice(i, 1);}// 方式2// for (let i = 0; i < arr.length; i++) {// console.log(arr.length);// // 注意點: 通過delete來刪除數(shù)組中的元素, 數(shù)組的length屬性不會發(fā)生變化// delete arr[i];// }console.log(arr);5.12 常用的清空數(shù)組的幾種方式:
let arr=[1,2,3,4,5];//方式1// arr=[];//方式2// arr.length=0;//方式3arr.splice(0,arr.length);5.13 如何判斷數(shù)組中是否包含某個元素
- 可以通過indexOf和lastIndexOf的結(jié)果, 判斷是否是-1即可
- 通過 includes() 方法
5.14 綜合案例
示例1:
//輸入0~9,輸出0~9中哪些數(shù)是用戶未輸入過的let str=prompt("請輸入三個整數(shù),用逗號隔開");let arr=str.split(",");let newArr=new Array(10);for(let i=0;i<arr.length;i++){let str=arr[i];newArr[str]=10;}for(let j=0;j<newArr.length;j++){if(newArr[j]===10){continue;}console.log(j);}// console.log(newArr);示例2:
//輸入5個0~9的數(shù)字,排序后輸出let str=prompt("請輸入五個整數(shù),用逗號隔開");let arr=str.split(",");let newArr=new Array(10);//數(shù)組中fill方法:設(shè)置數(shù)組中所有元素的值為指定的數(shù)據(jù)newArr.fill(0);for(let i=0;i<arr.length;i++){let str=arr[i];newArr[str]+=1;}for(let i=0;i<newArr.length;i++){for(let m=0;m<newArr[i];m++){console.log(i);}}示例3:
/*2.要求用戶輸入3個0~9的數(shù), 輸出0~9中哪些用戶沒有輸入過* 輸入的格式x,y,z* */let str = prompt("請輸入三個整數(shù), 用逗號隔開");// console.log(str); // 1,3,5// 字符串的split方法可以根據(jù)傳入的參數(shù)切割字符串, 轉(zhuǎn)換成一個數(shù)組之后返回給我們let arr = str.split(",");// console.log(arr);//方法1--擴展性不好/*for(let i = 0; i < 10; i++){if(arr[0] == i || arr[1] == i || arr[2] == i){continue;}console.log(i);}*//*方法2:推薦思路:定義一個長度為10的數(shù)組,不去設(shè)置它的初始值,那么這樣一來數(shù)組里面的每一個下標所對應(yīng)的值都是 undefined然后將輸入的值,比如“1,3,5”當(dāng)作新定義的數(shù)組的索引(下標),并且賦給一具體的值,比如 666,這樣一來的話那么新數(shù)組中索引為 1 3 5 的下標所對應(yīng)的值都為 666此時只需去循環(huán)新數(shù)組,并且判斷新數(shù)組中如果有索引值所對應(yīng)的數(shù)組內(nèi)容是 666 的,那么就退出當(dāng)前循環(huán),進行下一次循環(huán),輸出非 666 所對應(yīng)的索引即就是0~9中用戶沒有輸入過的數(shù)字*/// 0 1 2 3 4 5 6// [undefined, 666, undefined, 666, undefined, 666, undefined, undefined, undefined, undefined]let res = new Array(10);// 循環(huán)切割后形成的數(shù)組,for(let i = 0; i < arr.length; i++){// 取出用戶輸入的每個數(shù)let str = arr[i];// console.log(str);// 將取出的數(shù)當(dāng)作新數(shù)組的索引存入新數(shù)組,并賦一相同的固定值res[str] = 666;}// console.log(res);for(let i = 0; i < res.length; i++){if(res[i] === 666){continue;}console.log(i);}示例4:
/*2.從接盤接收5個0~9的數(shù)字, 排序后輸出* 輸入的格式x,y,z,...* 2, 6, 3, 8, 1* 2, 6, 3, 8, 3 --> 2,3,3,6,8* */// 0 1 2 3 4 5 6 7 8 9// [u, 6, 6, 6, u, u, 6, u, 6, u]// [u, u, 1, 2, u, u, 1, u, 1, u]// [0, 0, 1, 2, 0, 0, 1, 0, 1, 0]let str = prompt("請輸入五個整數(shù), 用逗號隔開");let arr = str.split(",");let res = new Array(10);// 數(shù)組的fill方法的作用: 設(shè)置數(shù)組中所有元素的值為指定的數(shù)據(jù)res.fill(0); // 將數(shù)組中所有的元素的值都設(shè)置為0// [2, 6, 3, 8, 3]// 遍歷用戶輸入的數(shù)據(jù)for(let i = 0; i < arr.length; i++){let str = arr[i]; // 2 6 3 8 3// 第一種//res[str]=6; // 有小問題 假設(shè)輸入:2, 6, 3, 8, 3,期望輸出:2,3,3,6,8,但是實際并不是/*res[2] = 0 + 1*/res[str] = res[str] + 1;}for(let i = 0; i < res.length; i++){// 第一種// if(res[i] === 6){// console.log(i);// }for(let j = 0; j < res[i]; j++){// console.log(i);console.log(i);// 輸出下標}}示例5
如果 compareFunction(a, b) 小于 0 ,那么 a 會被排列到 b 之前;
如果 compareFunction(a, b) 等于 0 , a 和 b 的相對位置不變。
如果 compareFunction(a, b) 大于 0 , b 會被排列到 a 之前
注意點: 如果元素是字符串類型, 那么比較的是字符串的Unicode編碼
let arr = ["c", "a", "b"];// if里面返回的和else if里面返回的要相反arr.sort(function(a, b) {if (a > b) {return -1; //降序} else if (a < b) {return 1;} else {return 0;}});console.log(arr);示例6
如果數(shù)組中的元素是數(shù)值類型
如果需要升序排序, 那么就返回a - b;
如果需要降序排序, 那么就返回b - a;
示例7
按元素長度排
let arr = ["1234", "21", "54321", "123", "6"];arr.sort(function(str1, str2) {// return str1.length - str2.length;//由短到長return str2.length - str1.length; //由長到短});console.log(arr);示例8
按對象的年齡排
let students = [{name: "zs",age: 34}, {name: "ls",age: 18}, {name: "ww",age: 22}, {name: "mm",age: 28}, ];students.sort(function(o1, o2) {// return o1.age - o2.age;//升序return o2.age - o1.age; //降序});console.log(students);六、二維數(shù)組概述
- 描述:數(shù)組中的元素為數(shù)組
- 語法:var arr=[[item1,item2],[item3,item4]…]
其實二維數(shù)組的調(diào)用很簡單,有兩個下標。第一個下標表示外層數(shù)組的下標,第二個下標表示內(nèi)層數(shù)組的下標。在這里就不去過多的去進行闡述了,相關(guān)用法和方法可以參考前面的數(shù)組里的方法。
一維數(shù)組及其相關(guān)方法
注意:
- 二維數(shù)組是一種特殊形式的數(shù)組,數(shù)組中的方法在二維數(shù)組中仍然適用
案例1:
<script>var infoArr = [['zhangsan', 22, 'male'],['lisi', 23, 'male'],['wangwu', 22, 'female']];console.log(infoArr); //[Array(3), Array(3), Array(3)]var newArr = infoArr[1];console.log(newArr); //["lisi", 23, "male"]var nameArr = newArr[0];console.log(nameArr); //lisiconsole.log(infoArr[1][1]); //23var allBookArr = [];var bookInfo1 = ['紅樓夢', '曹雪芹', '無價1'];var bookInfo2 = ['西游記', '吳承恩', '無價2'];var bookInfo3 = ['三國演義', '羅貫中', '無價3'];allBookArr.push(bookInfo1);allBookArr.push(bookInfo2);allBookArr.push(bookInfo3);console.log(allBookArr); //[Array(3), Array(3), Array(3)]console.log(allBookArr[1][1]); //吳承恩 </script>案例2:
// 循環(huán)錄入 5 名同學(xué)的姓名、身高、年齡,并將信息存入到二維數(shù)組里let students = [];for(let i = 0; i < 5; i++){let student = [];student.push(prompt("請輸入你的姓名:"));student.push(parseInt(prompt("請輸入你的年齡:")));student.push(parseFloat(prompt("請輸入你的身高:")));students.push(student);}// 用 table 的方式輸出console.log("姓名\t身高\t年齡");//循環(huán)輸出for(var j = 0; j < students.length; j++){console.log(students[j][0] + "\t" + students[j][1] + "\t" + students[j][2]);}//查找名稱為 張三 的學(xué)生,并刪除他的信息let index = -1;for(var k = 0; k < students.length; k++){if(students[k][0] == "張三"){index = k;break;}}if(index == -1){console.log("未找到該名學(xué)生!");}else {students.splice(index,1);}//根據(jù)學(xué)生的身高從高到低進行排序(選擇排序)// students.sort((a,b) => {// return a[2] - b[2];// })for(let l = 0; l < students.length - 1; l++){for(let m = l + 1; m < students.length; m++){if(students[l][2] > students[m][2]){let temp = students[l];students[l] = students[m];students[m] = temp;}}}console.log(students);總結(jié)
以上是生活随笔為你收集整理的JS基础之数组--概述、创建数组的几种方式、数组的特点、数组的常用方法、数组的解构赋值、数组高级API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 团队和过程:提升移动应用体验的根本
- 下一篇: 用Excel制作贪吃蛇