很多年不写前端代码了,我发现我连基础的 API 都不记得多少了。虽然看到别人写好的代码,我是轻松可以看懂的。但是能看懂和自己能写出来,差距是很大的。今天写项目中,遇到了一些数组的操作,我竟然多数都不知道怎么做。
如何判断一个数组是空的
let arr = []
if (arr.length == 0) {
console.log('empty')
else {
console.log('not empty')
}
判断一个数组是空的方法,就是判断数组的长度是不是0。
如何遍历一个数组,以及下标
let arr = ['a', 'b', 'c']
for (const e of arr) {
console.log(e)
}
for (const [idx, e] of arr.entries()) {
console.log('index is: ', idx, ' value is: ', e)
}
带下标遍历一个数组,可以用 entries() 方法。
判断一个元素在不在一个数组里
let arr = ['a', 'b', 'c'];
let element = 'b';
if (arr.includes(element)) {
console.log(`${element} is in the array.`);
} else {
console.log(`${element} is not in the array.`);
}
判断一个元素在不在数组里,可以用 includes() 方法。
在数组头尾插入元素
let arr = ['b', 'c']
let element = 'a'
let postfix = 'd'
arr.unshift(element)
arr.push(postfix)
使用 unshift 方法,可以在数组头部插入元素,push 可以在数组尾部插入元素。
判断数组元素下标和截断数组
let arr = ['a', 'b', 'c']
let element = 'b'
let index = arr.indexOf(element)
let removed
if (index !== -1) {
removed = arr.splice(index)
}
console.log(arr); // Output: ['a']
console.log(removed); // Output: ['b', 'c']
使用 splice() 方法,截断数组,包含传入的下标位置。
判断数组的每个元素,都是由字符串组成的
let arr = ['a', 'b', 'c']
if (arr.every( item => typeof item === 'string')) {
console.log('arr is an array of string')
}
可以使用 every 方法遍历数组,检查是不是所有元素都满足某个条件。
删除包含指定前缀的元素
给定一个字符串数组的数组,再给定一个搜索目标,也是一个字符串数组。 搜索以给定目标为前缀的数组,从所有范围删除。
// 定义一个函数来检查一个数组是否以另一个数组为前缀
function startsWith(array: any[], prefix: any[]): boolean {
if (prefix.length > array.length) {
return false;
}
for (let i = 0; i < prefix.length; i++) {
if (array[i] !== prefix[i]) {
return false;
}
}
return true;
}
// 数据数组
let data = [['a', 'b', 'c'], ['a', 'b'], ['b', 'c'], ['a', 'b', 'd']];
// 搜索目标
let target = ['a', 'b'];
// 过滤出那些不以搜索目标为前缀的数组
data = data.filter(array => !startsWith(array, target));
console.log(data); // Output: [ [ 'b', 'c' ] ]
上面这个相当于一个简单的算法题了。可以用 filter() 方法来过滤掉数组中不符合要求的元素。