No. | 內(nèi)容鏈接 |
---|---|
1 | Openlayers 【入門教程】 - 【源代碼+示例300+】 |
2 | Leaflet 【入門教程】 - 【源代碼+圖文示例 150+】 |
3 | Cesium 【入門教程】 - 【源代碼+圖文示例200+】 |
4 | MapboxGL【入門教程】 - 【源代碼+圖文示例150+】 |
5 | 前端就業(yè)寶典 【面試題+詳細答案 1000+】 |
在JavaScript中,刪除數(shù)組元素有以下幾種常用方法,包括它們的語法、注意事項和代碼示例:
一、五種方法
1. splice() 方法 - 刪除指定索引位置的元素
語法:
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
注意事項:
-
splice()
方法會直接修改原數(shù)組。 - 需要提供兩個參數(shù):起始索引
start
和要刪除的元素數(shù)量deleteCount
。 - 可選地,可以在刪除元素后在其位置插入新的元素。
代碼示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-858545.html
let myArray = [1, 2, 3, 4, 5];
myArray.splice(2, 1); // 刪除索引為2的元素
console.log(myArray); // 輸出: [1, 2, 4, 5]
// 同時刪除并插入元素
myArray.splice(2, 1, 'a', 'b');
console.log(myArray); // 輸出: [1, 2, 'a', 'b', 4, 5]
2. pop() 方法 - 刪除并返回數(shù)組最后一個元素
語法:
array.pop()
注意事項:
-
pop()
方法會直接修改原數(shù)組,減少數(shù)組長度。 - 它返回被刪除的最后一個元素。
代碼示例:
let myArray = [1, 2, 3];
let lastElement = myArray.pop();
console.log(lastElement); // 輸出: 3
console.log(myArray); // 輸出: [1, 2]
3. shift() 方法 - 刪除并返回數(shù)組第一個元素
語法:
array.shift()
注意事項:
-
shift()
方法同樣會直接修改原數(shù)組,減少數(shù)組長度。 - 它返回被刪除的第一個元素。
代碼示例:
let myArray = [1, 2, 3];
let firstElement = myArray.shift();
console.log(firstElement); // 輸出: 1
console.log(myArray); // 輸出: [2, 3]
4. delete 操作符 - 刪除指定索引位置的元素(保留數(shù)組長度,但使該位置值為 undefined)
注意事項:
-
delete
不是數(shù)組專用方法,而是JavaScript通用操作符。 - 使用
delete
會使得數(shù)組在相應索引上的值變?yōu)?undefined
,但數(shù)組長度不變。
代碼示例:
let myArray = [1, 2, 3, 4, 5];
delete myArray[2];
console.log(myArray); // 輸出: [1, 2, undefined, 4, 5]
5. 設置 length 屬性 - 快速刪除數(shù)組尾部之外的所有元素
注意事項:文章來源:http://www.zghlxwxcb.cn/news/detail-858545.html
- 直接設置數(shù)組的
length
屬性可以縮短數(shù)組,所有索引大于新length
值的元素都會被刪除。
代碼示例:
let myArray = [1, 2, 3, 4, 5];
myArray.length = 3;
console.log(myArray); // 輸出: [1, 2, 3]
二、注意事項總結(jié)
-
splice()
適合刪除任意位置的元素,且可以一次刪除多個。 -
pop()
和shift()
分別用于刪除末尾和頭部的單個元素。 - 使用
delete
操作符會導致數(shù)組中出現(xiàn)undefined
值,而非真正縮小數(shù)組大小。 - 調(diào)整
length
屬性可快速截斷數(shù)組,但請確保了解其對數(shù)組影響的特殊性。
到了這里,關于JS 刪除數(shù)組元素( 5種方法 )的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!