一、三点运算符
...扩展运算符可以将数组或者对象转为用逗号分隔的参数序列。
函数传不定参数,验证数组的长度
function demo(a,...b){
console.log(a,b);//b为数组 2,3,4,5
}
demo(1,2,3,4,5);
与结构使用
let [a,...b] = [1,2,3,4,5];
console.log(a,b);
与数组结构使用,函数传对象
function demo({username,password}){
console.log(username,password);
}
demo({username:'root',password:'123456'});
扩展运算符(...)
用...输出数组
const arr = [1,2,3];
console.log(...arr);
合并数组
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1,...arr2];
console.log(arr3);
将类数组转为真正的数组
const divEle = document.getElementsByTagName("div");
const arr = [...divEle];
console.log(arr);
let str = "1234";
console.log([...str]);
小练习
复制数组
const arr1 = [1,2,3];
const arr2 = [...arr1];
arr2[0]=5;
console.log(arr1,arr2);
创建一个函数,用扩展运算符计算两个数的和
function demo(a,b){
return a+b;
}
const arr1 = [1,2];
const arr2 = [4,5];
console.log(demo(...arr1));
console.log(demo(...arr2));
二、arr对象的方法
Array.from() 将伪数组或可遍历对象转换为真正的数组
let str = "1234";
const arr = Array.from(str);
console.log(arr);
const Arr = {
2:"a",
3:"b",
length:4, //是根据length的长度算的
}
console.log(Array.from(Arr));
array.find返回数组符合条件第一个元素的值
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
const arr = [1,2,3,4];
let num = arr.find(item=>item==3);
console.log(num);
找数组包对象
const arr = [
{realname:"张三1",age:18},
{realname:"张三2",age:17},
{realname:"张三3",age:19},
{realname:"张三4",age:17},
];
console.log(arr.find(item=>item.age==17));
array.findindex找到符合条件的第一个元素的索引
定义:用于找出第一个符合条件的数组成员的位置,如果没有找到返回-1。
const arr=[1,2,3,4];
console.log(arr.findIndex(item=>item==4));//3
const arrobj = [
{realname:"张三1",age:18},
{realname:"张三2",age:19},
{realname:"张三3",age:15},
{realname:"张三4",age:14},
]
console.log(arrobj.findIndex(item=>item.age==19));
array.includes() 找出某个数组是否包含给定的值
定义:判断某个数组是否包含给定的值,返回布尔值。
const arr=[1,2,3,4];
console.log(arr,includes(0));//有就返回true ,没有就返回false
三、字符串扩展方法
模板字符串的用法
function demo(){
return 'den';
}
let es6 ='es6!';
let str=`hello,${es6},${demo()};
startsWith和endsWith用法
- startsWith():表示参数字符串是否在原字符串的头部,返回布尔值
- endsWith():表示参数字符串是否在原字符串的尾部,返回布尔值
let str = "hello,es6!";
console.log(str.startsWith("hello"));//判断某个字符串前面是否包含hello 有就为true
console.log(str.endsWith("es6!"));//与startsWith相反
repeat字符串重复次数
repeat方法表示将原字符串重复n次,返回一个新字符串。
console.log('hello',repeat(4));