6. 数组和字符串扩展

"Hello World, Hello Blog"

Posted by wudimingwo on December 15, 2018

字符串回顾

  1. String.prototype.charAt(num);
    1
    2
    3
    
             let str = 'abcdefghijklmn';
             console.log(str.charAt(3));/ d
             console.log(str.charAt(3) == str[3]);/true
    
  2. String.prototype.charCodeAt(num);// 返回该字符的unicode码
    1
    
             console.log(str.charCodeAt(3));/100
    
  3. str.slice(start,end); [start,end) 左闭右开
    1
    
             console.log(str.slice(3,5));/ de
    
  4. str.indexOf(txt,start=0); 返回首次出现字符串的索引值, 没有则返回-1
    1
    2
    3
    
             console.log(str.indexOf('de'));/3
             console.log(str.indexOf('de',3));/3
             console.log(str.indexOf('de',4));/-1
    
  5. split(),toUpperCase(),toLowerCase()

es6 新增

  1. str.includes(txt,start=0) 字串的识别
    1
    2
    3
    
             console.log(str.includes('de'));/true
             console.log(str.includes('de',3));/true
             console.log(str.includes('de',4));/false
    
  2. str.startWidth(txt,start=0)[闭区间] str.endWidth(txt,end=length)(开区间)
    1
    2
    3
    4
    
             console.log(str.startsWith('ab'));/true
             console.log(str.startsWith('de',3));/true
             console.log(str.endsWith('mn'));/true
             console.log(str.endsWith('de',5));/true(不包含第5位)
    

    应用 前缀匹配, 域名分类

8.str.repeat(num);

1
2
3
4
5
6
7
8
9
10
11
12
13
产生由10个* 组成的字符串
最普遍
let str = '';
for(let i = 0;i < 10; i++) {
  str += '*';
}
console.log(str);

用repeat 

let str = '*'.repeate(10);

console.log(str);

模板字符串

1
2
3
4
5
            function returnStr (a,b) {
            	return `${a} * ${b} = ${a*b}`;
            }
            console.log(returnStr(5,2));/"5 * 2 = 10"
            

模板字符串的优点 更标准的字符串,更好的处理了字符串拼接的问题 语义化更好 防止注入XSS


标签模板 标签 => 函数

1
2
3
            alert('hello');/执行
            alert`hello1`;/ 执行
            alert'hello';/ 报错

试一下这个

1
            console.log`123`;

输出的是 image.png

看一下这个

1
2
3
4
5
6
7
8
            console.log(parseInt(`12${3}`));/ 123
            console.log(parseInt`12${3}`); /5
等价于 console.log(parseInt(['12',''],3)); /5


应该是先发生 ['12',''].toString() => '12,'
之后执行 parseInt('12,',3) => 5

看一下这个

1
2
3
4
5
6
7
            
            function print (arg1, arg2) {
            	console.log(arguments);
            	console.log(arg1,arg2);
            }
            
            print`12${3}4${5}6`;

image.png

1
2
3
4
5
6
7
8
            function print (listArr, ...arg) {
            	console.log(listArr);
            	console.log(arg);
            }
            let a = 10;
            let b = 5;
            
            print`${a} * ${b} = ${a*b}`;

image.png

有可能遇到攻击的情形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
正常
            let name = 'mike';
            document.write(`<p>你好,${name}</p>`)
插入脚本标签
              let name = '<script>console.log("over")</script>';
              document.write(`<p>你好,${name}</p>`)

处理
            
              let name = '<script>console.log("over")</script'+'>';
              function safeHTML (arr, name) {
                return `${arr[0]}${name.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')}${arr[1]}`
              }
              
              document.write(safeHTML`<p>你好,${name}</p>`)
            	

数组的扩展

  1. Array.of() 增强版 new Array() 统一返回由参数构成的数组
    1
    2
    3
    
               console.log(Array.of(9));/[9]
               console.log(Array.of('9'));/['9']
               console.log(Array.of('9',1,2));['9',1,2]
    

2.Array.from() 将类数组转换为数组 arguments Nodelist

1
2
3
            let oDivList = document.getElementsByTagName("div");
            	
            let realArr = Array.from(oDivList);

也可以用扩展运算符

1
            let realArr = [...oDivList];
  1. arr.find((item,index,self) => {}) arr.findIndex((item,index,self) => {}) 遇到符合条件的马上停止 ``` let arr = [1,2,3,4,5,NaN]; arr.find((x,y,z) => { return Object.is(x,NaN);/ NaN }) arr.findIndex((x,y,z) => { return Object.is(x,NaN);/5 })

如果没有 let arr = [1,2,3,4,5]; arr.find((x,y,z) => { return Object.is(x,NaN);/ undefined }) arr.findIndex((x,y,z) => { return Object.is(x,NaN);/-1 })

1
2
3
-------
4. arr.fill(value, start=0,end=length) 常用于初始化操作.
生成二维数组
1
2
3
4
5
       let arr = new Array(10);
       arr.fill(0);
       let list = new Array(10);
       list.fill(arr);
       console.log(list);

发现这样是不行的 let arr = []; arr.fill(0,0,10); let list = []; list.fill(arr,0,10); console.log(list);

```