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
东西。 属性是属于对象的变量。 我们的汽车对象将具有三个属性: make
, model
和color
。
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 。 所教授的技术包括HMTL , CSS , JavaScript , React , Redux , Node和Postgres 。 从头开始创建整个Web应用程序并获得行业第一份工作所需的一切。 费用为3,000英镑,下一个队列将于5月29日开始。 应用程序现已打开 。
翻译自: https://www.freecodecamp.org/news/javascript-objects-square-brackets-and-algorithms-e9a2916dc158/
相关文章:

《Java 8 实战》(二)—— Lambda
Lambda表达式可以理解为简洁地表示可传递的匿名函数的一种方式:它没有名称,但它有参数列表/函数主体/返回类型,可能还有一个可以抛出的异常列表。 Lambda表达式由参数/箭头和主体组成: (Apple a1, Apple a2) -> a1.getWeight(…

c++回调函数 callback
(1)Callback方式Callback的本质是设置一个函数指针进去,然后在需要需要触发某个事件时调用该方法, 比如Windows的窗口消息处理函数就是这种类型。比如下面的示例代码,我们在Download完成时需要触发一个通知外面的事件:…

【微信小程序之画布】终:手指触摸画板实现
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 先看效果图: wxml <!--pages/shouxieban/shouxieban.wxml--> <view class"container"><view>手写板(请在下方区域手写内容&…

Android开发中应避免的重大错误
by Varun Barad由Varun Barad Android开发中应避免的重大错误 (Critical mistakes to avoid in Android development) As many pioneers and leaders in different fields have paraphrased:正如许多不同领域的开拓者和领导人所说: In any endeavor, it is import…
机房收费系统(VB.NET)——超具体的报表制作过程
之前做机房收费系统用的报表是GridReport,这次VB.NET重构中用到了VisualStudio自带的报表控件。刚開始当然对这块功能非常不熟悉,只是探究了一段时间后还是把它做出来了。 以下把在VisualStudio(我用的是VisualStudio2013,假设与您…

微信小程序实现画布自适应各种手机尺寸
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 解决的问题: 画布,动画等js里面的操作,默认是px而不是rpx, 无法根据手机屏幕自适应 达到的效果: 让画布,动画在不同分辨…

网易新闻首页实现
http://www.2cto.com/kf/201409/330299.html IOS后台运行机制详解(二) http://blog.csdn.net/enuola/article/details/9148691转载于:https://www.cnblogs.com/itlover2013/p/4403061.html

阿联酋gitex_航空公司网站不在乎您的隐私后续行动:阿联酋航空以以下方式回应我的文章:...
阿联酋gitexby Konark Modi通过Konark Modi 航空公司网站不在乎您的隐私后续行动:阿联酋航空对我的文章进行了全面否认 (Airline websites don’t care about your privacy follow-up: Emirates responds to my article with full-on denial) Yesterday, The Regis…

微信小程序把缓存的数组动态渲染到页面
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 代码实现的目的:当页面销毁的时候,页面的参数状态还是能够保存。 show_img函数实现: 创建一个数组保存到缓存,遍历缓存的list_stutas对…

Find Minimumd in Rotated Sorted Array
二分搜索查最小数,from mid to分别为区间的第一个,中位数,和最后一个数 if(from<mid&&mid<to)//顺序,第一个即为最小值 return from; if(from>mid)//发现逆序,则最小值在这个区间,2分搜索…

在DataTable中更新、删除数据
在DataTable中选择记录 /*在DataTable中选择记录*//* 向DataTable中插入记录如上,更新和删除如下:* ----但是在更新和删除前,首先要找出要更新和删除的记录。* 一种方法是遍历DataRow,搜索想要的记录,* --〉然而更聪明的办法是使用…

使用TensorFlow进行机器学习即服务
by Kirill Dubovikov通过基里尔杜博维科夫(Kirill Dubovikov) 使用TensorFlow进行机器学习即服务 (Machine Learning as a Service with TensorFlow) Imagine this: you’ve gotten aboard the AI Hype Train and decided to develop an app which will analyze the effective…
浏览器加载、解析、渲染的过程
最近在学习性能优化,学习了雅虎军规 ,可是觉着有点云里雾里的,因为里面有些东西虽然自己也一直在使用,但是感觉不太明白所以然,比如减少DNS查询,css和js文件的顺序。所以就花了时间去了解浏览器的工作&…

《转》java设计模式--工厂方法模式(Factory Method)
本文转自:http://www.cnblogs.com/archimedes/p/java-factory-method-pattern.html 工厂方法模式(别名:虚拟构造) 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到其子类…

微信小程序去除左上角返回的按钮
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 解决方法有两种; 1.把该页面设置为tab页面或者主页 ; 2.进入该页面使用 wx.reLaunch(); 示例 wx.reLaunch({url: ../detail/detail,}) 这样有一个弊端,就是…

我的第一个web_登陆我的第一个全栈Web开发人员职位
我的第一个webby Robert Cooper罗伯特库珀(Robert Cooper) 登陆我的第一个全栈Web开发人员职位 (Landing My First Full Stack Web Developer Job) This is the story of the steps I took to get my first job as a full stack web developer. I think it’s valuable to sha…

HTTP请求报文和HTTP响应报文(转)
原文地址:http://blog.csdn.net/zhangliang_571/article/details/23508953 HTTP报文是面向文本的,报文中的每一个字段都是一些ASCII码串,各个字段的长度是不确定的。HTTP有两类报文:请求报文和响应报文。 HTTP请求报文 一个HTTP请…

微信小程序用户未授权bug解决方法,微信小程序获取用户信息失败解决方法
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: bug示例图: 导致这个bug的原因是 wx.getUserInfo(OBJECT) 接口做了调整; 请看官方文档的描述: wx.getUserInfo(OBJECT) 注意:此接口有…

格式化json日期'/Date(-62135596800000)/'
日期经过json序列化之后,变成了/Date(-62135596800000)/字符串,在显示数据时,我们需要解释成正常的日期。 Insus.NET和js库中,写了一个jQuery扩展方法: $.extend({JsonDateParse: function (value) {if (value /Date(…

aws lambda使用_使用AWS Lambda安排Slack消息
aws lambda使用Migrating to serverless brings a lot of questions. How do you do some of the non-serverless tasks, such as a cronjob in a serverless application?迁移到无服务器带来了很多问题。 您如何执行一些非无服务器的任务,例如无服务器应用程序中的…

微信小程序模块化开发 include与模板开发 template
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 1. include 是引用整个wxml文件,我通常会配合js,css一起使用; 使用场景,需要封装事件和微信 api 的公共模块。 2.template ÿ…

winform解析json
在使用C#开发爬虫程序时,会遇到需要解析json字符串的情况。对于json字符串可以使用正则表达式的形式进行解析,更为方便的方法是使用Newtonsoft.Json来实现。 Nuget添加应用包 在工程上右键——【管理Nuget程序包】浏览找到要安装的程序包Newtonsoft.Jso…

Oracle11g密码忘记处理方法
c:\>sqlplus /nolog sql>connect / as sysdba sql>alter user 用户名 identified by 密码;(注意在这里输入的密码是区分大小写的) 改完之后你可以输入 sql>connect 用户名/密码 as sysdba进行验证 转载于:https://www.cnblogs.com/imhuanxi…

hic染色体构想_了解微服务:从构想到起点
hic染色体构想by Michael Douglass迈克尔道格拉斯(Michael Douglass) 了解微服务:从构想到起点 (Understanding Microservices: From Idea To Starting Line) Over the last two months, I have invested most of my free time learning the complete ins-and-outs…

[python]关于字符串查找和re正则表达式的效率对比
最近需要在python中做大日志文件中做正则匹配 开始直接在for in 中每行做re.findall,后来发现,性能不行,就在re前面做一个基本的字符串包含判断 (str in str),如果不包含直接continue 效率对比: 1、只做一次包含判断&a…

微信小程序客服功能 把当前页面的信息卡片发送给客服
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 正文: 需求:微信小程序客服带详情页 , 场景:一个人通过微信小程序接入微信客服,聊天后带上入口链接 效果图: 写法: …

phpcms标签大全V9
转自:http://blog.csdn.net/cloudday/article/details/7343448调用头部 尾部{template "content","header"} 、 {template "content","footer"}{siteurl($siteid)} 首页链接地址 <a href"{siteurl($siteid)}/&q…

多伦多到温莎_我想要freeCodeCamp Toronto的Twitter来发布报价,所以我做了一个免费的bot来做到这一点。...
多伦多到温莎If you read About time, you’ll know that I’m a big believer in spending time now on building things that save time in the future. To this end, I built a simple Twitter bot in Go that would occasionally post links to my articles and keep my ac…

Linux常用命令汇总(持续更新中)
命令说明注意点cat access.log | wc -l统计行数awk命令可以做到同样的想过:cat access.log | awk END {print NR}grep vnc /var/log/messages查看系统报错日志等同于:sudo dmesg -T | grep "(java)"netstat -lnt | grep 590*查看端口状态 nets…

IOS问题汇总:2012-12-18 UIAlertView+UIActionSheet
UIAlertView/UIActionSheet UIAlertView * alertView [[UIAlertView alloc] initWithTitle:“添加场景模式” message:“请输入场景名称” delegate:self cancelButtonTitle:“取消” otherButtonTitles:“确定”, nil];alertView.alertViewStyle UIAlertViewStylePlainTextI…