TypeScript数组和对象的操作
一、数组的声明
let arr1:Array<number>;let arr2:number[];
二、数组初始化
let arr1:Array<number>=newArray<number>();let arr2:number[]=[1,2,3];
三、数组元素赋值、添加、更改
// 基本变量不需要声明后可以不需要初始化;let a:number;
a =1;console.log(a);// 1let b:string;
b ="string";console.log(b);// string// 数组和对象使用之前必须要初始化;let arr1:Array<number>;// arr1[0] = 100; // Variable 'arr1' is used before being assigned.//arr1.push(100); // 就算使用push来添加也不行//console.log(arr1)let arr2:Array<number>=newArray<number>();
arr2[0]=1;// 赋值和修改格式一样
arr2.push(2);// 最后面增加,可以多个值
arr2.unshift(3)// 最前面增加,可以多个值console.log(arr2)// [3, 1, 2, 3]
四、删除
let arr:Array<number>=[1,2,3,4,5]
arr.pop();console.log(arr);// [1, 2, 3, 4]
arr.shift();console.log(arr);// [2, 3, 4]
arr.splice(0,2);// 删除元素(index, deleteCount)console.log(arr);// [4]
五、合并、断开数组
let arr:Array<number>=[1,2,3]let arr2:Array<number>=[4,5,6]let arrValue =7
arr = arr.concat(arr2)console.log(arr)//[1, 2, 3, 4, 5, 6]
arr = arr.concat(arrValue)console.log(arr)//[1, 2, 3, 4, 5, 6, 7] let newArray = arr.slice(1,3)console.log(newArray)// [2,3]
六、查找数组元素
let arr:Array<string>=["a","b","c","d"]let index = arr.indexOf("c")//返回查找到的第一个元素所在位置console.log(index)// 2
index = arr.lastIndexOf("d")//返回反序查找的第一个元素所在位置console.log(index)// 3// 对象let persons =[{ id:1, name:'张三', age:23},{ id:2, name:'李四', age:11},{ id:3, name:'王五', age:16}];// persons.forEach((value, index, array) => {// console.log(value, index)// })// find() 方法返回相应的对象, 从未返回真值,则 find() 方法返回 undefinedconst person = persons.find(obj =>{return obj.id ===2;})console.log(person);// { "id": 2, "name": "李四", "age": 11} // filter, 也可以反向选择const p1 = persons.filter(obj =>{// return obj.name != "李四"return obj.id ==2;})console.log(p1);// { "id": 2, "name": "李四", "age": 11} const p2 = persons.filter(obj =>{return obj.id !=2;})console.log(p2);/**
[{
"id": 1,
"name": "张三",
"age": 23
}, {
"id": 3,
"name": "王五",
"age": 16
}]
*/// 查找元素的indexconst c1 = persons.findIndex(person =>{return person.name =="李四"})console.log(c1);// 1console.log(persons[c1])//{ "id": 2, "name": "李四", "age": 11}
七、连接数组元素
let arr:Array<string>=["a","b","c","d"]let joinString = arr.join(",")//返回查找到的第一个元素所在位置console.log(joinString)// "a,b,c,d"
joinString = arr.join("-")//返回反序查找的第一个元素所在位置console.log(joinString)// "a-b-c-d"
八、排序、反序数组
let arr:Array<number>=[1,4,3,5,2]
arr.sort()console.log(arr)// [1, 2, 3, 4, 5]
arr.reverse()//返回反序查找的第一个元素所在位置console.log(arr)// [5, 4, 3, 2, 1]
九、遍历数组,对象
- 定义数组
let persons =[{ id:1, name:'张三', age:23},{ id:2, name:'李四', age:11},{ id:3, name:'王五', age:16}];
- for 循环
for(let index =0; index < persons.length;++index){console.log(persons[index]);}
- for…in 循环
for(let index in persons){console.log(persons[index])}
- for…of循环
for(let person of persons){console.log(person)}
- forEach循环
persons.forEach((value, index, array)=>{console.log(value, index)})
本文转载自: https://blog.csdn.net/book_longker/article/details/132520436
版权归原作者 book_longker 所有, 如有侵权,请联系我们删除。
版权归原作者 book_longker 所有, 如有侵权,请联系我们删除。