欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js解构赋值

程序员文章站 2024-02-20 20:45:28
...

解构赋值

  • 解构赋值可以同时对一组变量进行赋值
     var array = ['李雷','韩梅梅','老王'];
     //传统方式
     var a = array[0];
     var b = array[1];
     var c = array[2];
     //解构赋值
     var [d,e,f] = array;
     console.log('d = ' + d);
     console.log('e = ' + e);
     console.log('f = ' + f);
  • 在解构赋值的时候,要注意嵌套层次和位置保持完全一致
    var [x,[y,z]] = ['李雷',['韩梅梅','老王']];
    console.log('x = ' + x);
    console.log('y = ' + y);
    console.log('z = ' + z);
  • 只对一个变量赋值
	var [,,o] = array;
	console.log('o = ' + o);
  • 从对象中取出若干属性,可以使用解构赋值
    var person = {
        name: '元芳',
        age: 20,
        sex: '不明',
        school: '狄仁杰大学',
        address:{
            city: '王者荣耀峡谷',
            phone: 18188888888
        }
    };

    var {name,age,sex,school} = person;
    console.log('name = ' + name);
    console.log('age = ' + age);
    console.log('sex = ' + sex);
    console.log('school = ' + school);

    var {name:username,address:{city,phone}} = person;
    console.log('name = ' + username);
    console.log('city = ' + city);
    console.log('phone = ' + phone);
  • 交换两个数的值
    var x = 5, y = 6;
    [x,y] = [y,x];
    console.log('x = ' + x);
    console.log('y = ' + y);