ES6中for循环、函数扩展、字符串扩展、创建类

一、for循环:

1.for:
var arr = ['a','b','c'];

console.log("for:");
for(var i = 0; i < arr.length; i++){
    console.log("键", i, "值", arr[i]);
};
2.forEach:
var arr = ['a','b','c'];
console.log("===============");
console.log("forEach:");
//遍历:数组  参数一:当前元素  参数二:当前元素的索引值
arr.forEach(function (term, index) {
    console.log("键", index, "值", term);
});
3.for in:
var arr = ['a','b','c'];
console.log("===============");
console.log("for in:");
//遍历:数组,对象;     推荐遍历对象,因为它的下标是字符串
for(var index in arr){
    console.log("键", index, "值", arr[index])
}
4.for of:
console.log("===============");
console.log("for of:");
//遍历:数组,字符串,映射,集合等数据结构   只取出值,
var set = new Set([1,2,3,4]);
//for of获取值
for(var val of set){
    console.log("值", val);
}

var a = ['g','d','j'];
//for of获取数组索引  
//keys():从数组中创建迭代对象,该对象包含了数组的键;返回的是一个迭代对象
for(var index of arr.keys()){
    console.log(index);
}

二、函数扩展:

1.ES6以后函数的参数可以写默认值
function f(name = "jhh", age = 20) {
    console.log("name", name, "age", age);
}
f();
2.箭头函数:
/*
    箭头函数:
        当函数只有一个参数时,小括号可以不写;当函数体只有一句代码的时候大括号可以不写
*/
//1.没有参数
var fn = () => console.log("jhhhhhhhhh");
fn();

//2.有一个参数
var fn2 = a => console.log(a);
fn2(1);

//3.有多个参数 函数体有多行代码
var fn3 = (a,b) => {
    console.log("a:", a, "b:", b);
    console.log("你好啊箭头函数");
};
fn3(1,2);
4.rest和arguments:
/*
    arguments:获取所有实参;
    rest:获取函数多余的参数;
    ES6语法以后rest替换了arguments;
    rest相较于arguments更灵活
 */

function fn4() {
	//[Arguments] { '0': 1, '1': 2, '2': 3, '3': 5, '4': 4 }
    console.log(arguments); 
}
fn4(1,2,3,5,4);

//第一个参数赋值给a,剩下的参数全部赋值给vals
function fn5(a,...vals) {
	console.log(a); 	//1
    console.log(vals);  //[ 2, 3, 5, 4 ]
}
fn5(1,2,3,5,4);

三、字符串扩展:

1.repeat函数:指定平铺的次数
var str = "chun";
console.log(str.repeat(3));
2.模板字符串:传统js中通过 “+” 拼接html,现在使用反引号;需要添加变量直接${}
var a = "hh";
var html = `
    <ul>
        <li>哈哈哈</li>
        <li>嘻嘻嘻</li>
        <li>嘿嘿嘿</li>
        <li>${a}</li>
    </ul>
`;
console.log(html);

四、创建类

//创建一个类
class Person {
    constructor(name, age){
        //this表示公有,var表示私有
        this.name = name;
        this.age = age;
        this.sayName = () =>{
            return this.name;
        }
    }
}
var person = new Person("jhh",20);
console.log(person);
console.log(person.sayName());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值