js 操作字符串,

字符串补全

'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))

字符串内容测试

  1. 'abcdef'.includes('c');//true  
  2. 'abcdef'.includes('ye');//false  
  3. 'abcdef'.startsWith('a');//true  
  4. 'abcdef'.endsWitch('f');//true  
  5. //includes(), startsWith(), endsWith() 都支持第二个参数,  
  6. //类型为数字类型,意为从第 n 个字符开始,endsWith()的第二个参数有点不一样  
  7. 'abcdef'.includes('c', 4);//false 从第5个字符开始查找是否有 'c' 这个字符  
  8. 'abcdef'.startsWith('d', 3);//true 从第4个字符开始查找是否是以 'd' 字符为开头  
  9. 'abcdef'.endsWith('d', 4);//true 前面的4个字符里,是否以 'd' 字符为结尾 

数组合并

  1. let a = [1, 2];  
  2. let b = [3];  
  3. let c = [2, 4];  
  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
}

发布了42 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/wzwzwz555/article/details/102785723
今日推荐