TypeScript arrays

1. Array declaration

// 数组声明
let arr1: number[] = [];
let arr2: number[] = new Array(4);              // 指定数组长度
let arr3: number[] = new Array(1, 2, 3, 4, 5);  // 初始化数组
let arr4: Array<number> = new Array<number>();

// 后续测试都用该数组
let arr: number[] = new Array(1, 2, 3, 4, 5);

2. Array traversal (for...of)

for…ofCan be used to iterate over objects with iterators

for (let item of arr) {
    
    
    console.log(item);
}
// 1, 2, 3, 4, 5

for (let item in arr) {
    
    
    console.log(item);
}
// 0, 1, 2, 3, 4 (数组下标)

3. Method

3.1 every()

Checks whether each element of the numeric element meets the condition

let result1 = arr.every((val, idx, ary) => val <= 3);	// false
let result2 = arr.every((val, idx, ary) => val <= 5);	// true

3.2 filter()

Detect numeric elements and return an array of all elements that meet the criteria

let result3 = arr.filter((val, idx, ary) => val > 3);	// [4, 5]

3.3 forEach()

The callback function is executed once for each element of the array

 let result4 = arr3.forEach((val, idx, ary) => {
    
    console.log(val)});	// 1, 2, 3, 4, 5

3.4 indexOf()

Searches for an element in an array and returns its position. If the search cannot be found, the return value is -1, which means there is no item

let result5 = arr3.indexOf(3);
let result6 = arr3.indexOf(6);
console.log(result5, result6);	//  2  -1

3.5 lastIndexOf()

Returns the position of the last occurrence of a specified string value, searching from the back to the front at the specified position in a string

3.6 map()

Process each element of the array by the specified function and return the processed array

let result7 = arr.map((val, idx, arr) => val += 1);
console.log(result7);		// [2, 3, 4, 5, 6]

3.7 push()

Adds one or more elements to the end of the array and returns the new length

arr.push(6);
console.log(arr);		// [1, 2, 3, 4, 5, 6]

3.8 pop()

Removes the last element of an array and returns the removed element

3.9 shift()

Remove and return the first element of the array

3.10 some()

Checks whether any element in the array element meets the specified condition

おすすめ

転載: blog.csdn.net/weixin_45136016/article/details/130109790