這篇文章主要介紹了js數組的常用方法有哪些的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇js數組的常用方法有哪些文章都會有所收獲,下面我們一起來看看吧。
數組的常用方法有下面幾種
方法 釋義
push()
push()?法可以接收任意數量的參數,并將它們添加到數組末尾,返回數組的最新?度
unshift()
unshift() 在數組開頭添加任意多個值,然后返回新的數組?度
splice()
傳?三個參數,分別是開始位置、 0 (要刪除的元素數量)、插?的元素,返回空數組
concat()
?先會創建?個當前數組的副本,然后再把它的參數添加到副本末尾,最后返回這個新構建的數組,不會影響原始數組
pop()
pop() ?法?于刪除數組的最后?項,同時減少數組的 length 值,返回被刪除的項
shift()
shift() ?法?于刪除數組的第?項,同時減少數組的 length 值,返回被刪除的項
splice()
傳?兩個參數,分別是開始位置,刪除元素的數量,返回包含刪除元素的數組
slice()
slice() ?于創建?個包含原有數組中?個或多個元素的新數組,不會影響原始數組
indexOf()
返回要查找的元素在數組中的位置,如果沒找到則返回 -1
includes()
返回要查找的元素在數組中的位置,找到返回 true ,否則 false
find()
返回第?個匹配的元素
數組的兩個排序方法
reverse() 反轉數組
let values = [1, 2, 3, 4, 5];
values.reverse();
alert(values); // 5,4,3,2,1
sort()
sort() ?法接受?個?較函數,?于判斷哪個值應該排在前?
數組方法的基本操作
增
數組基本操作可以歸納為 增、刪、改、查,需要留意的是哪些?法會對原數組產?影響,哪些?法不會
push()
let colors = []; // 創建?個數組
let count = colors.push("red", "green"); // 推?兩項
console.log(count) // 2
unshift()
let colors = new Array(); // 創建?個數組
let count = colors.unshift("red", "green"); // 從數組開頭推?兩項
alert(count); // 2
splice()
let colors = ["red", "green", "blue"];
let removed = colors.splice(1, 0, "yellow", "orange")
console.log(colors) // red,yellow,orange,green,blue
console.log(removed) // []
concat()
let colors = ["red", "green", "blue"];
let colors2 = colors.concat("yellow", ["black", "brown"]);
console.log(colors); // ["red", "green","blue"]
console.log(colors2); // ["red", "green", "blue", "yellow", "black",
"brown"]
刪
pop()
let colors = ["red", "green"]
let item = colors.pop(); // 取得最后?項
console.log(item) // green
console.log(colors.length) // 1
shift()
let colors = ["red", "green"]
let item = colors.shift(); // 取得第?項
console.log(item) // red
console.log(colors.length) // 1
splice()
let colors = ["red", "green", "blue"];
let removed = colors.splice(0,1); // 刪除第?項
console.log(colors); // green,blue
console.log(removed); // red,只有?個元素的數組
1234
slice()
let colors = ["red", "green", "blue", "yellow", "purple"];
let colors2 = colors.slice(1);
let colors3 = colors.slice(1, 4);
console.log(colors) // red,green,blue,yellow,purple
concole.log(colors2); // green,blue,yellow,purple
concole.log(colors3); // green,blue,yellow
改
splice()
let colors = ["red", "green", "blue"];
let removed = colors.splice(1, 1, "red", "purple"); // 插?兩個值,刪除?個元素
console.log(colors); // red,red,purple,blue
console.log(removed); // green,只有?個元素的數組
查
indexOf()
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.indexOf(4) // 3
includes()
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.includes(4) // true
find()
const people = [
{
name: "Matt",
age: 27
},
{
name: "Nicholas",
age: 29
}
];
people.find((element, index, array) => element.age < 28) // // {name:
"Matt", age: 27}
關于“js數組的常用方法有哪些”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“js數組的常用方法有哪些”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。