字符串
字符串扩展 substring(start,stop) 不包含stop, substr(start,length), indexOf() 首次出现的位置
let str = 'hello world';
str.startsWith('h');
startsWith()判断字符串是否在原字符串的头部,返回true/false,区分大小写,第二个参数表示搜索的位置
endswith()判断字符串是否在原字符串的尾部,第二个参数表示搜索的位置
indexOf()判断字符串在原字符串中第一次出现的位置/索引
includes()匹配是否存在于字符串,第二个参数表示搜索的位置
字符串循环 for of
for(let s of 'helloworld'){
console.log(s) //h e l l ....
};
repeat()重复
//repeat() 重复
'a'.repeat(5); //aaaaa
'abc'.repeat(3); //abcabcabc
'abc'.repeat(0); //''
'abc'.repeat(3.6); //取整
补全
//补全
let s2 = 'a';
s2.padStart(5,'xyz'); //xyzxa 头部补全
s2.padEnd(5,'xyz'); //axyzx 尾部补全
其中,5代表补全之后字符串长度
数值扩展
parseInt(2.2345);
Number.parseInt(2.2345);
//判断一个数值是否为整数
Number.isInteger(10); //true
Number.isInteger(10.342); //false
//Math 对象 执行数学任务
Math.random() //随机数 0-1 但不包含0/1
Math.ceil(3.6) //向上 4
Math.floor(3.9) //向上 3
Math.round(3.9) //四舍五入
Math.trunc(3.6) //3
Math.trunc(-3.6) //-3
Math.sign(-3.6) //判断数值是正数,负数,零。。。。
//正数 +1 负数 -1 0 0 其它值 NaN
ES6的指数运算符
a**=2 => a = a**2 => a = a*a;
2**2 = 4,3**2 = 9;
rest参数
function fun(...values){ //arguments
console.log(values) //values[2]
};
fun(2,32,343,324,34,432,5325,24,432,42,42);
箭头函数
let f = v=>v;
let f = function(v){
return v;
};
//参数为空
let f = ()=>'123';
//多个参数
let f = (n1,n2)=>n1+n2;
let f = (n1,n2)=>{abc()};
//对象
let f = (n1,n2)=>({name:n1,age:n2});
//传默认值
let f = (n1,n2=10)=>{
console.log(n1,n2)
};
f(3) //3 10
箭头函数不能作为构造函数,不能使用new
var f = () =>{}
var f1 = new f(); //f is not a constructor
var f2 = () =>{}
f2.prototype; //error
this的指向
function Fun(){
this.i = 0;
setTimeout(function(){
console.log(this); //window
},2000);
};
var f3 = new Fun();
//es6
function Fun(){
this.i = 0;
setTimeout(()=>{
console.log(this); //Fun()
},2000);
};
var f3 = new Fun();
// 对象中箭头函数的方法表示window对象
var obj = {
age:18,
getAgeA:function(){
console.log(this.age) //Obj
},
getAgeB:()=>{
console.log(this.age) //window
}
};
obj.getAgeA();
obj.getAgeB();
//对象中箭头函数如何外层调用者的方式
var obj = {
age:18,
getAgeA:function(){
var fn =()=> this.age; Obj
return fn();
}
};
obj.getAgeA();
扩展运算符
var arr1 = [1,2,3];
var arr2 = [4,5,6];
arr1 = arr1.concat(arr2); //[1, 2, 3, 4, 5, 6]
//ES6
var arr1 = [1,2,3];
var arr2 = [4,5,6,7,9,10];
arr1.push(...arr2); //[1, 2, 3, 4, 5, 6]
利用扩展运算符进行数组的深拷贝:
普通的方式将一个数组的数组名赋给另一个变量只能进行浅拷贝
var a1 = [1,2,3,4];
var a2 = a1;
a2[1] = 100;
console.log(a1); //1,100,3,4
可以使用数组的方法进行深拷贝,例如上例,a2 = a1.concat(); 或者slice();
更简便的方法是使用扩展运算符...
a2 = [...a1];
在数组的合并中,arr1 = arr1.concat(arr2,arr3);
也可以是arr1 = [...arr2,...arr3];
在解构中
var [a,b,c,d] = [1,2,3,4];
var [a,...b] = [1,2,3,4]; //ok
a //1
b //[2,3,4];
var [...a,b] = [1,2,3,4]; //error 扩展运算符只能放在参数的最后一位,否则报错
var [a,...b,c] = [1,2,3,4]; //error
扩展运算符同样适用于字符串
var str = 'hello';
console.log(str.split('')); //["h", "e", "l", "l", "o"]
//es6
var str = 'hello';
[...str]; ["h", "e", "l", "l", "o"]