实用的js操作

作者: 一支桨 | 来源:发表于2019-07-04 17:12 被阅读0次

    记录下本人在学习过程中觉得比较好的小例子,整理成笔记,便于后来查看

    • 判断数据类型
    //判断对象的数据类型
    const isType = type =>target =>`[object ${type}]`===Object.prototype.toString.call(target);
    const isArray=isType("Array");
    console.log(isArray([]))
    
    • 数组去重
    const arr = [1,2,2,2,6,6,6,5];
    //method one
    console.log(Array.from(new Set(arr))) //[1,2,6,5]
    //method two
    console.log([...new Set(arr)])   //[1,2,6,5]
    
    • 对象合并,...扩展运算符
    let obj1 = {name:"san zhang",age:15};
    let obj2 = {name:"san zhang",sex:"male",like:"basketball"};
    let newobj = {...obj1,...obj2};
    console.log(newobj);   //{name: "san zhang", age: 15, sex: "male", like: "basketball"}
    
    • 数组的遍历方法(not Arrap.Map)
    let users =[{name:"Jack",age:15},{name:"Rose",age:18},{name:"Tom",age:16}];
    console.log(Array.from(users,{name}=>name));  //["Jack", "Rose", "Tom"]
    //equal map
    console.log(users.map(user=>user.name))
    
    • ...运算符 and 解构赋值
    let userInfo ={
      name:"老学长",
      age:15,
      classroom:"15-1",
      birthday:"10.5",
      sex:"male"
    }
    let baseInfo={},user ={};
    ({name:baseInfo.name,sex:baseInfo.sex,...user} = userInfo);
    console.log(baseInfo);  //{name: "老学长", sex: "male"}
    console.log(user);  //{age: 15, classroom: "15-1", birthday: "10.5"}
    
    • 属性名动态赋值
    let key = "name";
    let obj = {
      [key]:"big brother"
    }
    console.log(obj)  //{name: "big brother"}
    

    相关文章

      网友评论

        本文标题:实用的js操作

        本文链接:https://www.haomeiwen.com/subject/rpkrhctx.html