jquery 增加與刪除數組元素


1.數組元素的添加

demoArray.push(value);

1 var demo=new Array();
2        var key=[4,5];
3        demo.push(1);//插入數字
4        demo.push(key);//插入一個數組
5        demo.push("字符串");//插入字符串
6        demo.push("str");

2.數組元素的刪除

demoArray.splice(startPos,deleteCount);

1 demo.splice(0,2);//從下標為0的元素開始,向后刪除兩個元素

3.jQuery提供的快捷查找方法

$.inArray(value,array);//返回值為value第一次在array數組中出現的位置(下標從0開始).
1 var pos=$.inArray(1,demo);//返回1在數組dem第一次出現的位置的下標.

4.結合上述內容編寫的一個刪除數組指定元素的實例函數.

function delValInArr(value,array){
           var pos=$.inArray(value,array);
           array.splice(pos,1);
}

 

5.ES6 提供了兩個數組的實例查找相關的方法

① Array.find

② Array.findIndex

下面舉例說明

1 /**
2  * 普通純數值的數組,查找指定內容的下標
3  **/
4 let testArr=[1,3,5,2,3];
5 //查找數值為5的第一個數的下標
6 let index=testArr.findIndex(v=>{
7     return v===5;
8 })
9 console.log(index);//2
 1 /**
 2  * 復雜數組的查找
 3  */
 4 //測試數據
 5 let testArr = [
 6     { name: '小明1', id: 7, age: 18 },
 7     { name: '小明1', id: 8, age: 18 },
 8     { name: '小明2', id: 9, age: 19 },
 9     { name: '小明3', id: 10, age: 20 }
10 ]
11 //查找id為9的第一組數據
12 let res = testArr.find(v => {
13     return v.id === 9;
14 })
15 //查找id為9的第一組數據的下標
16 let resIndex = testArr.findIndex(v => {
17     return v.id === 9;
18 })
19 console.log('res :', res);//res : {name: "小明2", id: 9, age: 19}
20 console.log('resIndex :', resIndex);//resIndex : 2

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM