by Dmitri Grabov

德米特里·格拉波夫(Dmitri Grabov)

JavaScript对象,方括号和算法 (JavaScript Objects, Square Brackets and Algorithms)

One of the most powerful aspects of JavaScript is being able to dynamically refer to properties of objects. In this article we will look at how this works and what advantages this might give us. We will take a quick look at some of the data structures used in Computer Science. In addition we will look at something called Big O notation which is used to describe the performance of an algorithm.

JavaScript最强大的方面之一是能够动态引用对象的属性。 在本文中,我们将研究它的工作原理以及它可能给我们带来的好处。 我们将快速浏览一下计算机科学中使用的一些数据结构。 此外,我们还将介绍一种称为Big O的符号,该符号用于描述算法的性能。

对象介绍 (Objects intro)

Let’s begin by creating a simple object representing a car. Each object has something called properties. A property is a variable that belongs to an object. Our car object will have three properties: make, model and color.

首先创建一个代表汽车的简单对象。 每个对象都有一个称为properties东西。 属性是属于对象的变量。 我们的汽车对象将具有三个属性: makemodelcolor

Let’s see what it could look like:

让我们看看它看起来像什么:

const car = {  make: 'Ford',  model: 'Fiesta',  color: 'Red'};

We can refer to individual properties of an object using dot notation. For example, if we wanted to find out what the color of our car is, we can use dot notation like this car.color.

我们可以使用点表示法来引用对象的各个属性。 例如,如果我们想找出汽车的颜色,可以使用像car.color这样的点符号。

We could even output it using console.log:

我们甚至可以使用console.log将其输出:

console.log(car.color); //outputs: Red

Another way to refer to a property is using square bracket notation:

引用属性的另一种方法是使用方括号表示法:

console.log(car['color']); //outputs: Red

In the above example, we use the property name as a string inside square brackets to get the value corresponding to that property name. The useful thing about square bracket notation is that we can also use variables to get properties dynamically.

在上面的示例中,我们使用属性名称作为方括号内的字符串,以获取与该属性名称相对应的值。 关于方括号表示法的有用之处在于,我们还可以使用变量来动态获取属性。

That is, rather than hardcoding a specific property name, we can specify it as a string in a variable:

也就是说,我们可以将其指定为字符串中的变量,而不是对特定的属性名称进行硬编码:

const propertyName = 'color';const console.log(car[propertyName]); //outputs: Red

使用带有方括号符号的动态查找 (Using dynamic lookup with square bracket notation)

Let’s look at an example where we can use this. Let’s say we run a restaurant and we want to be able to get the prices of items on our menu. One way doing this is using if/else statements.

让我们看一个可以使用它的示例。 假设我们经营一家餐厅,并且希望能够获得菜单上的商品价格。 一种方法是使用if/else语句。

Let’s write a function which will accept an item name and return a price:

让我们编写一个函数,该函数将接受商品名称并返回价格:

function getPrice(itemName){  if(itemName === 'burger') {    return 10;  } else if(itemName === 'fries') {    return 3;  } else if(itemName === 'coleslaw') {    return 4;  } else if(itemName === 'coke') {    return 2;  } else if(itemName === 'beer') {    return 5;  }}

While the above approach works, it’s not ideal. We have hardcoded the menu in our code. Now if our menu changes, we will have to rewrite our code and redeploy it. In addition, we could have a long menu and having to write all this code would be cumbersome.

尽管上述方法可行,但并不理想。 我们已经在代码中对菜单进行了硬编码。 现在,如果菜单发生更改,我们将不得不重写代码并重新部署它。 另外,我们的菜单可能很长,必须编写所有这些代码会很麻烦。

A better approach would be to separate our data and our logic. The data will contain our menu and the logic will look up prices from that menu.

更好的方法是将我们的数据和逻辑分开。 数据将包含我们的菜单,逻辑将从该菜单中查找价格。

We can represent the menu as an object where the property name, also known as a key, corresponds to a value.

我们可以将menu表示为一个对象,其中属性名称(也称为键)对应于一个值。

In this case the key will be the item name and value will be the item price:

在这种情况下,键将是商品名称,值将是商品价格:

const menu = {  burger: 10,  fries: 3,  coleslaw: 4,  coke: 2,  beer: 5};

Using square bracket notation we can create a function which will accept two arguments:

使用方括号表示法,我们可以创建一个将接受两个参数的函数:

  • a menu object菜单对象
  • a string with item name带有项目名称的字符串

and return the price of that item:

并返回该商品的价格:

const menu = {  burger: 10,  fries: 3,  coleslaw: 4,  coke: 2,  beer: 5};
function getPrice(itemName, menu){  const itemPrice = menu[itemName];  return itemPrice;}
const priceOfBurger = getPrice('burger', menu);console.log(priceOfBurger); // outputs: 10

The neat thing about this approach is that we have separated our data from our logic. In this example, the data lives in our code, but it could just as easily be coming from a database or API. It is no longer tightly coupled with our lookup logic which converts item name to item price.

这种方法的优点是我们已经将数据与逻辑分离了。 在此示例中,数据保存在我们的代码中,但也很可能来自数据库或API。 它不再与将商品名称转换为商品价格的查询逻辑紧密结合。

数据结构和算法 (Datastructures and algorithms)

A map in Computer Science terms is a data structure which is a collection of key/value pairs where each key maps to a corresponding value. We can use it to look a value which corresponds to a specific key. This is what we are doing in the previous example. We have a key which is an item name and we can look up the corresponding price of that item using our menu object. We are using an object to implement a map data structure.

用计算机科学术语来说,映射是一种数据结构,它是键/值对的集合,其中每个键都映射到相应的值。 我们可以使用它来查找对应于特定键的值。 这就是我们在前面的示例中所做的。 我们有一个键,即商品名称,我们可以使用菜单对象查找该商品的相应价格。 我们正在使用一个对象来实现地图数据结构。

Let’s look at an example of why we may want to use a map. Let’s say we run a book shop and have a list of books. Each book has a unique indentifier called International Standard Book Number (ISBN), which is a 13 digit number. We store our books in an array and want to be able to look them up using the ISBN.

让我们看一个为什么我们可能要使用地图的例子。 假设我们经营一家书店,并有一个书单。 每本书都有一个唯一的标识符,称为国际标准书号(ISBN),它是一个13位数字。 我们将图书存储在一个数组中,希望能够使用ISBN进行查找。

One way of doing so is by looping over the array, checking the ISBN value of each book and if it matches returning it:

一种方法是通过遍历数组,检查每本书的ISBN值以及是否匹配返回值:

const books = [{  isbn: '978-0099540946',  author: 'Mikhail Bulgakov',  title: 'Master and Margarita'}, {  isbn: '978-0596517748',  author: 'Douglas Crockford',  title: 'JavaScript: The Good Parts'}, {  isbn: '978-1593275846',  author: 'Marijn Haverbeke',  title: 'Eloquent JavaScript'}];
function getBookByIsbn(isbn, books){  for(let i = 0; i < books.length; i++){    if(books[i].isbn === isbn) {      return books[i];    }  }}
const myBook = getBookByIsbn('978-1593275846', books);

That works fine in this example since we only have three books (it’s a small book shop). However, if we were Amazon, iterating over millions of books could be very slow and computationally expensive.

在此示例中,这很好用,因为我们只有三本书(这是一家小书店)。 但是,如果我们是亚马逊,那么遍历数百万本书可能会非常缓慢且计算量很大。

Big O notation is used in Computer Science to describe the performance of an algorithm. For example if n is the number of books in our collection, the cost of using iteration to look up a book in the worst case scenario (the book we look for is last in the list) will be O(n). That means if the number of books in our collection doubles, the cost of finding a book using iteration will double as well.

Big O符号在计算机科学中用于描述算法的性能。 例如,如果n是我们集合中的书的数量,则在最坏的情况下(我们寻找的书在列表中的最后),使用迭代查找书的成本为O(n) 。 这意味着,如果我们的藏书数量翻倍,那么使用迭代查找书籍的成本也会增加一倍。

Let’s take a look at how we can make our algorithm more efficient by using a different data structure.

让我们看一下如何通过使用不同的数据结构来提高算法的效率。

As discussed, a map can be used to look up the value which corresponds to a key. We can structure our data as map instead of an array by using an object.

如所讨论的,可以使用映射来查找对应于键的值。 我们可以使用对象将数据构造为地图而不是数组。

The key will be the ISBN and the value will be the corresponding book object:

密钥将是ISBN,值将是相应的书本对象:

const books = {  '978-0099540946':{    isbn: '978-0099540946',    author: 'Mikhail Bulgakov',    title: 'Master and Margarita'  },  '978-0596517748': {    isbn: '978-0596517748',    author: 'Douglas Crockford',    title: 'JavaScript: The Good Parts'  },  '978-1593275846': {    isbn: '978-1593275846',    author: 'Marijn Haverbeke',    title: 'Eloquent JavaScript'  }};
function getBookByIsbn(isbn, books){  return books[isbn];}
const myBook = getBookByIsbn('978-1593275846', books);

Instead of using iteration, we can now use a simple map lookup by ISBN to get our value. We no longer need to check the ISBN value for each object. We get the value directly from the map using the key.

现在,我们可以使用ISBN的简单映射查找代替使用迭代来获取价值。 我们不再需要检查每个对象的ISBN值。 我们使用键直接从地图中获取值。

In terms of performance, a map lookup will provide a huge improvement over iteration. This is because the map lookup has constant cost in terms of computation. This can be written using Big O notation as O(1). It does not matter if we have three or three million books, we can get the book we want just as fast by doing a map lookup using the ISBN key.

在性能方面,映射查找将在迭代方面提供巨大的改进。 这是因为映射查找在计算方面具有恒定的成本。 可以使用Big O表示形式将其写为O(1) 。 不管我们拥有三三百万本书,我们都可以通过使用ISBN键进行地图查找来快速获得想要的书。

回顾 (Recap)

  • We have seen we can access the values of object properties using dot notation and square bracket notation我们已经看到我们可以使用点表示法和方括号表示法访问对象属性的值
  • We learned how we can dynamically look up values of property by using variables with square bracket notation我们了解了如何通过使用带方括号符号的变量来动态查找属性值
  • We have also learned that a map datastructure maps keys to values. We can use keys to directly look up values in a map which we implement using an object.我们还了解到,映射数据结构将键映射到值。 我们可以使用键直接在使用对象实现的地图中查找值。
  • We had a first glance at how algorithm performance is described using Big O notation. In addition, we saw how we can improve the performance of a search by converting an array of objects into a map and using direct lookup rather than iteration.

    我们第一眼看到了如何使用Big O表示法描述算法性能。 此外,我们看到了如何通过将对象数组转换为映射并使用直接查找而不是迭代来提高搜索性能的方法。

Want to test your new found skills? Try the Crash Override exercise on Codewars.

是否想测试您发现的新技能? 在Codewars上尝试“ 崩溃替代”练习。

Want to learn how to write web applications using JavaScript? I run Constructor Labs, a 12 week JavaScript coding bootcamp in London. The technologies taught include HMTL, CSS, JavaScript, React, Redux, Node and Postgres. Everything you need to create an entire web app from scratch and get your first job in the industry. Fees are £3,000 and next cohort starts on 29th May. Applications are open now.

是否想学习如何使用JavaScript编写Web应用程序? 我在伦敦进行了为期12周的JavaScript编码训练营的Constructor Labs 。 所教授的技术包括HMTLCSSJavaScriptReactReduxNodePostgres 。 从头开始创建整个Web应用程序并获得行业第一份工作所需的一切。 费用为3,000英镑,下一个队列将于5月29日开始。 应用程序现已打开 。

翻译自: https://www.freecodecamp.org/news/javascript-objects-square-brackets-and-algorithms-e9a2916dc158/

JavaScript对象,方括号和算法相关推荐

  1. Javascript的数据结构与算法(一)

    1数组 1.1方法列表 数组的常用方法如下: concat: 链接两个或者更多数据,并返回结果. every: 对数组中的每一项运行给定的函数,如果该函数对每一项都返回true,则返回true. fi ...

  2. 如何正确克隆JavaScript对象?

    我有一个对象x . 我想将其复制为对象y ,以使对y更改不会修改x . 我意识到,复制从内置JavaScript对象派生的对象将导致额外的不需要的属性. 这不是问题,因为我正在复制自己的文字构造对象之 ...

  3. JavaScript 面试中常见算法问题详解

    JavaScript 面试中常见算法问题详解,翻译自 https://github.com/kennymkchan/interview-questions-in-javascript.下文提到的很多问 ...

  4. 如何判断Javascript对象是否存在

    Javascript语言的设计不够严谨,很多地方一不小心就会出错. 举例来说,请考虑以下情况. 现在,我们要判断一个全局对象myObj是否存在,如果不存在,就对它进行声明.用自然语言描述的算法如下: ...

  5. JavaScript对象、JSON对象、JSON字符串的区别

    一.首先看下什么是JSON JSON:JavaScript Object Natation,JavaScript对象的表现形式,已经发展成一种轻量级的数据交换格式. JavaScript对象的表现形式 ...

  6. JavaScript 对象总结

    JavaScript 中的所有事物都是对象:字符串.数值.数组.函数... 此外,JavaScript 允许自定义对象 JavaScript 对象 对象只是一种特殊的数据.对象拥有属性和方法 访问对象 ...

  7. java 反射 判断是否存在_如何判断Javascript对象是否存在

    Javascript语言的设计不够严谨,很多地方一不小心就会出错. 举例来说,请考虑以下情况. 现在,我们要判断一个全局对象myObj是否存在,如果不存在,就对它进行声明.用自然语言描述的算法如下: ...

  8. JS 复习(6)JavaScript对象

    JavaScript对象 在 JavaScript 中,对象是一组无序的相关属性和方法的集合,所有的事物都是对象,例如字符串.数值.数组.函数等. 对象是一个具体的事物,看得见摸得着的实物. 对象是由 ...

  9. 笔记--javascript对象及简单,复杂数据类型

    javascript 对象 1. 对象 什么是对象 ? 在 javascript 中,对象是一组无序的相关属性和方法的集合,所有的事物都是对象,例如字符串,数值,数组,函数等.对象是由属性和方法组成的 ...

最新文章

  1. tensorflow.transpose() 举例
  2. python实现文件共享_改进的一行Python实现文件共享--支持并发
  3. Linux下mysql备份
  4. 判断用户是否存在再进行新增_基于tableau从商业分析模型角度对业务数据进行多维度分析--【商业分析类】...
  5. sap.ca.scfld.md.Startup.init('cus.crm.notes', this);
  6. EFCore之SQL扩展组件BeetleX.EFCore.Extension
  7. 新闻发布项目——实体类(categoryTB)
  8. centos8 挂载ntfs_CentOS 8 挂载NTFS系统磁盘方案
  9. 论文浅尝 | 基于知识图谱的子图匹配回答自然语言问题
  10. 连续性的设计——改善产品的体验
  11. CSS中的类class和标识id选择符(.和#号)
  12. vue前端验证输入_Vue-Element之vue-element 输入框验证
  13. c语言 运行库 下载,Visual C++运行库合集
  14. html打印表格样式,HTML打印表格
  15. [项目管理]-第九章:项目管理计划
  16. 层次分析法(附实例)
  17. java数字转为大写_java 数字转大写汉字
  18. 投影仪对焦应用镜头马达驱动芯片
  19. aac格式怎么转换为MP3格式
  20. html 一键复制 ios,h5实现一键复制到粘贴板-兼容ios

热门文章

  1. spark编程基础--5.2键值对RDD
  2. 软件工程实训有必要吗_人工智能专业值得读吗?就业如何?
  3. 小程序使用富文本完整代码及示例图
  4. 微信小程序获取用户收货地址 完整代码
  5. iOS UICollectionView实现瀑布流(3)
  6. MediaCodeC解码视频指定帧,迅捷、精确
  7. 理解 CSS 布局和块级格式上下文
  8. POJO、JavaBean、DAO
  9. springBoot PUT请求接收不了参数的解决办法
  10. Linux字符设备驱动程序的框架(新写法)