首页 > web前端 > js教程 > 正文

JavaScript - 解构数组和对象 [实时文档]

王林
发布: 2024-08-21 08:00:36
转载
1022人浏览过

javascript - 解构数组和对象 [实时文档]

  • 孤立地学习新主题,否则头脑将无法长期完全掌握这个概念。这也得到了一些实证研究的支持。
  • 解构:将数组或对象中的值解包到单独变量中的方法。
const nums = [8,4,5];
const num1 = nums[0];
const num2 = nums[1];
const num3 = nums[2];
console.log(num1, num2, num3);

is reduced to 

const [x,y,z] = nums;
console.log(x, y, z);

three const variables named x,y,z are created in this step
登录后复制
  • [x,y,z] 虽然看起来像一个数组,但是当它位于 = 的 lhs 上时,则被视为解构。
  • 解构是不可变的操作。
const girl = {
  name: 'melania',
  friends: ['alina', 'alice', 'ayesha', 'anamika', 'anaya'],
  eats: ['roasted', 'pizza', 'burger', 'rice', 'manchurian'],
};

const [first, second] = girl.friends;
console.log(first, second);

const [,,,fourth,last] = girl.eats;
console.log(fourth, last);
登录后复制

交换变量[变异]

let array = [5,6];
let [a,b] = array;
console.log(`a: ${a}, b:${b}`);
[b,a] = [a,b];
console.log(`a: ${a}, b:${b}`);
登录后复制

函数返回一个数组,立即破坏结果,这允许我们从函数返回多个值

const girl = {
  name: 'melania',
  friends: ['alina', 'alice', 'ayesha', 'anamika', 'anaya'],
  eats: ['roasted', 'pizza', 'burger', 'rice', 'manchurian'],
  drinks: ['juice','coffee','coke'],
  order: function(eat,drink){
    return [this.eats[eat],this.drinks[drink]];
  }
};

const [maincourse, drinks] = girl.order(2, 2);

console.log(`maincourse: ${maincourse}`);
console.log(`drinks: ${drinks}`);
登录后复制

解构嵌套数组

let nums = [5,3,[8,7,9,3]];
let [x,y,z] = nums;
console.log(`x: ${x}`); // 5
console.log(`y: ${y}`); // 3
console.log(`z: ${z}`); // 8,7,9,3

let nums2 = [5,3,[8,7]];
let [x,,[y,z]] = nums2;
console.log(`x: ${x}`, `y: ${y}`, `z: ${z}`); // 5 8 7 
登录后复制

从未知大小的数组解构:

const names = ['michael','charlie','peter'];
let [w='xxx',x='xxx',y='xxx',z='xxx'] = names;
console.log(w,x,y,z); // 'michael' 'charlie' 'peter' 'xxx'
登录后复制

解构对象:

Calliper 文档对比神器
Calliper 文档对比神器

文档内容对比神器

Calliper 文档对比神器 28
查看详情 Calliper 文档对比神器
  • 使用 {} 进行对象解构,使用 [] 进行数组解构。
  • 提供要提取的对象属性名称中提到的准确变量名称。这些变量名称的顺序并不重要。
const girl = {
  name: 'melania',
  friends: ['alina', 'alice', 'ayesha', 'anamika', 'anaya'],
  eats: ['roasted', 'pizza', 'burger', 'rice', 'manchurian'],
  drinks: ['juice','coffee','coke'],
  works: {
        mtwt: {
          start: 9,
          end: 5
        },
        fri: {
          start:9,
          end: 3
        }
  }
};

const {name, works, drinks} = girl;
console.log(name);
console.log(works);
console.log(drinks);


// replace long property names with custom names:
const {name:user, works:timings, drinks:enjoys} = girl;
console.log(user);
console.log(timings);
console.log(enjoys);


//destructuring data from api calls returned in the form of objects i.e attaching a default value to a property that does not exist on object received from an api call

// details does not exist, so default value is assigned
const { details = [], eats: loves = [] } = girl;
console.log(details);
// eats exist but is renamed as loves, hence default value won't apply
console.log(loves);
登录后复制
## mutating variables using object destructuring
let x = 10;
let y = 20;
let obj = {x:1, y:2, z:3};

{x,y} = obj; // error
when we start a line with a '{', then js expects a code-block. and we cannot assign anything to a code-block on lhs using = operator. hence, an error is thrown. the error is resolved by wrapping into () as shown below
({x,y} = obj); //{ x: 1, y: 2, z: 3 }
登录后复制

解构嵌套对象

const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
  drinks: ['Juice','Coffee','Coke'],
  works: {
        mtwt: {
          start: 9,
          end: 5
        },
        fri: {
          start:10,
          end: 2
        }
  }
};

let { fri } = works;
console.log(fri);

// Destructuring the fri object using the same property names start, end
let {fri: {start, end}} = works;
console.log(start, end);

// Further renaming for shortening start as 'b' and end as 'e'
let {fri: {start: b, end: e}} = works;
console.log(b, e);





const girl = {
  name: 'Melania',
  friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'],
  eats: ['Roasted', 'Pizza', 'Burger', 'Rice', 'Manchurian'],
  drinks: ['Juice','Coffee','Coke'],
  works: {
        mtwt: {
          start: 9,
          end: 5
        },
        fri: {
          start:10,
          end: 2
        }
  },
  // these destructured property-names have to be same as they are passed inside the girl.sleep(). Order need not be same.
  sleep: function ({time='NA', address='NA', color = 'NA', duration='NA'}){
    console.log(`${this.name} sleeps at ${address} for ${duration} in ${color}light for ${duration}. She loves to eat ${this.eats[0]}`);
  }
};

// A single object is passed, which will be destructured by the method inside the object extracting all values via destructuring
girl.sleep({time: '10pm', address:'home', color: 'blue', duration: '7hrs'});

girl.sleep({time: '9pm', duration: '7hrs'});
登录后复制

以上就是JavaScript - 解构数组和对象 [实时文档]的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号