JavaScript对象,方括号和算法

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值