字符串补全
'12345'.padStart(7, '0')//0012345 - 字符串不足7位,在头部补充不足长度的目标字符串
'12345'.padEnd(7, '0')//1234500 - 在尾部进行字符串补全
字符串转换成数组
Array.of(3,4,5)//[3,4,5]
字符串重复输出
var str='1,2,3';
重复输出5遍
console.log(str.repeat(5))
字符串内容测试
- 'abcdef'.includes('c');//true
- 'abcdef'.includes('ye');//false
- 'abcdef'.startsWith('a');//true
- 'abcdef'.endsWitch('f');//true
- //includes(), startsWith(), endsWith() 都支持第二个参数,
- //类型为数字类型,意为从第 n 个字符开始,endsWith()的第二个参数有点不一样
- 'abcdef'.includes('c', 4);//false 从第5个字符开始查找是否有 'c' 这个字符
- 'abcdef'.startsWith('d', 3);//true 从第4个字符开始查找是否是以 'd' 字符为开头
- 'abcdef'.endsWith('d', 4);//true 前面的4个字符里,是否以 'd' 字符为结尾
数组合并
- let a = [1, 2];
- let b = [3];
- let c = [2, 4];
- let d = [...a, ...b, ...c];//[1, 2, 3, 2, 4] 所有内容合并,但未去重复
两个数组去重
function array_diff(a, b) { for (var i = 0; i < b.length; i++) { for (var j = 0; j < a.length; j++) { if (a[j].id == b[i].id) { a.splice(j, 1); j = j - 1; } } } return a; }
单个元素在数组去重
1 es6新特性
function distinct(a, b) { return Array.from(new Set([...a, ...b])) }
2 首先创建一个空对象,然后用 for 循环遍历
利用对象的属性不会重复这一特性,校验数组元素是否重复
function distinct(a, b) {
let arr = a.concat(b)
let result = []
let obj = {}
for (let i of arr) {
if (!obj[i]) {
result.push(i)
obj[i] = 1
}
}
return result
}
3 使用双重for循环去重
function distinct(a, b) {
let arr = a.concat(b);
for (let i=0, len=arr.length; i<len; i++) {
for (let j=i+1; j<len; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1);
// splice 会改变数组长度,所以要将数组长度 len 和下标 j 减一
len--;
j--;
}
}
}
return arr
}