Previously, I shared my usage of padStart to elegantly replace what would’ve been loads of if statements. This magical method threw me off my rocker. I simply couldn’t believe it existed.

之前 ,我分享了padStart用法,以优雅地替换if语句的负载。 这种神奇的方法把我甩了下来。 我简直不敢相信它的存在。

它能做什么 (What it does)

Mozilla Developer Network (MDN) Docs:

Mozilla开发人员网络(MDN)文档 :

The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.

padStart()方法用另一个字符串(如果需要,重复padStart()当前字符串,以使结果字符串达到给定的长度。 从当前字符串的开头(左侧)开始应用填充。

Keep prepending a string to another string until the target length is met.

继续在另一个字符串 前添加一个字符串 ,直到达到目标长度为止。

If the length is already less than the original string’s length, nothing happens.

如果长度已经小于原始字符串的长度,则什么也不会发生。

And since padStart returns a string, we can chain its methods.

而且由于padStart返回一个字符串,我们可以链接其方法。

See? 1, 2, 3, 4, and 5 are all less than or equal to world's length of 5, so padStart doesn’t do anything.

看到? 1、2、3、4和5均小于或等于world 5的长度,因此padStart不会执行任何操作。

浏览器支持 (Browser support)

Unfortunately, support’s currently “meh”

不幸的是,支持目前是“ meh”

Desktop supportMobile support
桌面支持 行动支援

You can either use babel-polyfill or the polyfill by MDN.

您可以使用babel-polyfill或MDN的polyfill 。

Here’s MDN’s polyfill.

这是MDN的polyfill。

一些兴趣点: (Some points of interest:)

  • Prototypes (lines 1 and 2)

    原型 (第1行和第2行)

  • Bitwise operators (line 4)

    按位运算符 (第4行)

  • padString.repeat (line 14)

    padString.repeat (第14行)

  • padString.slice (line 17)

    padString.slice (第17行)

I’m down to step through them if you are ?

如果您是我,我将逐步通过他们。

Lines 1 and 2 aren’t that bad: “If padStart isn’t supported by the browser, let’s create our own padStart and add it” (that’s polyfill-ing in a nutshell).

第1行和第2行还不错:“如果浏览器不支持padStart ,让我们创建自己的padStart并添加它”(简而言之,就是polyfill-ing)。

A common way to check a method’s browser support is to inspect its object’s prototype. Since padStart is a string method, it should exist on String.prototype.

检查方法的浏览器支持的一种常见方法是检查其对象的原型。 由于padStart是一个字符串方法,因此它应该存在于String.prototype

My old version of Safari doesn’t support padStart.

我的旧版Safari不支持padStart

My Safari’s padStart support

But my Chrome and Firefox do.

但是我的Chrome和Firefox可以。

Chrome padStart supportFirefox padStart support
Chrome padStart支持 Firefox padStart支持

Consider this safety check on line 1

考虑第1行的安全检查

if (!String.prototype.padStart) {
}

That if statement would only return true in my old Safari. It returns false in Chrome/Firefox, so no polyfill-ing happens.

if语句仅在我的旧版Safari中返回true 。 在Chrome / Firefox中,它返回false ,因此不会进行填充。

Moving on, line 2 creates a new function called padStart and assigns it to String.prototype.padStart. Because of JavaScript’s inheritance model, any string created afterwards can use padStart.

继续,第2行创建了一个名为padStart的新函数,并将其分配给String.prototype.padStart 。 由于JavaScript的继承模型,以后创建的任何字符串都可以使用padStart

This function takes two parameters

该函数有两个参数

1. targetLength: How long should the resulting string be?

1. targetLength :结果字符串应targetLength多长时间?

2. padString: What are we padding it with?

2. padString :我们要用它填充什么?

Let’s shower this code with debugger statements.

让我们用debugger语句来编写此代码。

I also removed that if statement from line 1, so even the native String.prototype.padStart will be overridden by this function–makes it useful if you want to debug in Chrome.

我还从第1行中删除了if语句,因此,即使是本机String.prototype.padStart也将被该函数覆盖-如果您想在Chrome中进行调试,则它很有用。

Don’t override prototypes in production, kids!

孩子们,不要超越生产中的原型!

Using our initial example

使用我们的初始示例

'world'.padStart(11, 'hello ');

Check out line 2. We see that targetLength and padString made their way into our function. No craziness yet, but it’s coming. I’ve been avoiding line 5 long enough.

targetLength第2行。我们看到targetLengthpadString进入了我们的函数。 还没有疯狂,但它来了。 我一直在避开5号线足够长时间。

按位运算符 (Bitwise operators)

The comment above line 5 briefly describes its purpose: “If targetLength is a number, round it down. If it’s not a number, make it 0”.

第5行上方的注释简要描述了其目的:“如果targetLength是数字,则将其四舍五入。 如果不是数字,则将其设置为0”。

Bitwise operators make this possible.

按位运算符使之成为可能。

targetLength >> 0;

targetLength >> 0;

This operator >> is known as a sign-propagating right shift (LOLWUT?). You use it with two numbers

此运算符>>被称为符号传播右移 (LOLWUT?)。 您使用两个数字

a >> b

a >> b

What this does:

这是做什么的:

  1. a is converted into binary (details here).

    a转换为二进制( 此处有详细信息 )。

  2. Binary a gets right-shifted b times.

    二进制a 右移 b次。

Our targetLength is 11–that’s 1011 in binary (here’s a converter if you don’t believe me ?).

我们的targetLength为11 –二进制为1011(如果您不相信我,这里是一个转换器 )。

A side effect of converting to binary is that numbers get rounded down and most non-numbers become 0.

转换为二进制的副作用是数字将四舍五入, 大多数非数字变为0。

Try the following examples

尝试以下示例

See? Fractions become whole numbers. Non-numbers become 0, with one notable exception…

看到? 分数变成整数。 非数字变为0,但有一个例外:

Binary is just 1’s and 0’s, right? Those 1’s and 0’s represent “on” and “off” switches–true and false. true's binary form is 1, and false's binary form is 0. Just keep that in mind.

二进制只是1和0,对吧? 那些1和0代表“ on”和“ off”开关truefalsetrue的二进制形式为1, false的二进制形式为0。请记住这一点。

So now that we’ve “sanitized” targetLength, we begin the right-shifting.

现在,我们已经“清理”了targetLength ,我们开始右移。

Right-shift means you move each bit to the right n times. That’s it.

右移意味着您将每个位右移n次。 而已。

Here’s a PowerPoint visualization of 11 >> 1 (I forgot how great PowerPoint actually is).

这是11 >> 1的PowerPoint可视化效果(我忘记了PowerPoint到底有多出色)。

Turn 11 into 1011 and right-shift it 1 time. Your end result is 101, which is 5 in binary.

将11变成1011,然后右移1次。 您的最终结果是101,即二进制5。

But our code says targetLength >> 0.

但是我们的代码说targetLength >> 0

所以我们右移0次... (So we’re right-shifting 0 times…)

The whole point of right-shifting 0 times is to abuse that side effect of converting targetLength into binary. We don’t actually want to shift anything because that’ll change the value.

右移0次的全部目的是滥用将targetLength转换为二进制的targetLength 。 我们实际上并不想转移任何东西,因为那会改变价值。

继续 (Moving on)

Jump to line 7’s debugger now. targetLength has been sanitized. Next!

现在跳到第7行的debuggertargetLengthtargetLength下一个!

Line 11.

第11行。

padString = String(padString || ' ');

If we don’t provide a padString argument, it defaults to an empty space. I actually never noticed until now.

如果不提供padString参数,则默认为空白。 直到现在我才真正注意到。

Line 17.

第17行。

Notice how line 13 had another safety check, “If the original string’s length is greater than targetLength, don’t do anything. Just return the original string”

注意第13行如何进行另一次安全检查,“如果原始字符串的长度大于targetLength ,则不要执行任何操作。 只需返回原始字符串”

That makes sense because if our targetLength is 1, but the string is already 10 characters, what’s the point? We demonstrated that earlier with

这是有道理的,因为如果我们的targetLength为1,但是字符串已经是10个字符,那有什么意义呢? 我们之前用

// just returns 'world'
'world'.padStart(0, 'hello ');

Line 18 determines how many more characters we need by subtracting targetLength from the original string’s length. We need 6, in this case.

第18行通过从原始字符串的长度中减去targetLength来确定我们还需要多少字符。 在这种情况下,我们需要6。

Line 27.

第27行。

We skipped that if statement on line 20 because targetLength and padString.length just happened to be the same, but we’ll revisit that soon.

我们跳过了第20行上的if语句,因为targetLengthpadString.length恰好是相同的,但是我们很快会再次讨论。

For now, we’re stopped right before line 29. Let’s break it up.

现在,我们在第29行之前停了下来。让我们分解一下。

padString.slice(0, targetLength);

The good old String.prototype.slice method.

好的旧String.prototype.slice方法。

MDN Docs:

MDN文件

The slice() method extracts a section of a string and returns it as a new string.

slice()方法提取字符串的一部分,并将其作为新字符串返回。

It’s index-based, so we’re starting at index 0 of padString, and grabbing the amount of characters equal to targetLength. It’s kind of like

它基于索引,因此我们从padString索引0 padString ,并获取等于targetLength的字符targetLength 。 有点像

Return that sliced padString combined with the original string, and you’re done!

返回切成薄片的padString与原始字符串的组合,就完成了!

完成了 (Almost done)

I’d normally conclude here, but we haven’t explored that if statement on line 20. To make sure we hit it this time, let’s try another earlier example

我通常会在这里得出结论,但是我们没有探讨第20行上的if语句。为确保这次我们成功了,让我们尝试另一个较早的示例

'yo'.padStart(20, 'yo');

I skipped to line 20 because we already know what happens up to this point.

我跳到第20行,因为我们已经知道到目前为止发生了什么。

if (targetLength > padString.length)

if (targetLength > padString.length)

targetLength is 18, and padString is 'yo', with 2 as its length. 18 > 2, so what next?

targetLength为18, padString'yo' ,其长度为2。 18> 2,接下来呢?

padString += padString.repeat(targetLength / padString.length);

Remember, padStart returns a sliced padString + original string. If you want to pad 'yo' with 'yo' until it’s 20 characters long, you’ll have to repeat many times. This is where that logic happens, using padString.repeat.

记住, padStart返回一个切片的 padString +原始字符串。 如果你想垫'yo''yo' ,直到它的20个字符长,你必须重复多次。 这就是使用padString.repeat逻辑处理的padString.repeat

MDN Docs:

MDN文件

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

repeat()方法构造并返回一个新字符串,该字符串包含指定数量的被调用的字符串的副本,并串联在一起。

So it copy/pastes the string n times.

因此,它将字符串复制/粘贴n次。

In order to find out how many repeats we need, divide targetLength by padString.length.

为了找出我们需要多少次重复,将targetLength除以padString.length

Repeat 'yo' 9 times and get a string of 'yo's that is 18 characters long. Add that to your original 'yo', and your final count is 20 characters.

重复'yo'次,并得到一个18字符长的'yo'字符串。 将其添加到原始的'yo' ,最终计数为20个字符。

Mission accomplished. Until next time!

任务完成。 直到下一次!

翻译自: https://www.freecodecamp.org/news/how-does-string-padstart-actually-work-abba34d982e/

String.padStart实际如何工作?相关推荐

  1. babel工作笔记001---babel从入门到入门

    技术交流QQ群[JAVA,.NET,BigData,AI]:170933152 1.babel是什么 2.javascript制作规范 3.babel转译器 4.babel的使用 5.常见的几种bab ...

  2. Java中String、StringBuffer和StringBuilder的区别

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6581009.html  在编程中,对于字符串拼接,我们可以用String类重载的+或concat(str).S ...

  3. string类型加减_测试人员应该知道的Redis知识(四) String

    一.概述 完整的说,应该是Binary-safe string,二进制安全字符串.从官网内容我们可以看到,String类型是最简单的一种数据类型,和Memcached的类型一致,一个key对应一个va ...

  4. string 相等 java_java中string相等问题(==与.equal的具体区别。求详细解释)

    展开全部 这要和String的JVM内部工作原理相结合! 比如:String s1="accp" Java内部将此62616964757a686964616fe58685e5aeb ...

  5. Java实例——基于jsoup的简单爬虫实现(从智联获取工作信息)

    这几天在学习Java解析xml,突然想到Dom能不能解析html,结果试了半天行不通,然后就去查了一些资料,发现很多人都在用Jsoup解析html文件,然后研究了一下,写了一个简单的实例,感觉还有很多 ...

  6. 使用poi统计工作职责

    1 创建一个新的sheet工作页 Sheet job = workbook.createSheet("工作职责统计"); 2 查询工作职责问题选项列表,并设置第一行倒出时间 Lis ...

  7. padStart 和 padEnd的使用

    padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串.从当前字符串的末尾(右侧)开始填充. 语法:str.padEnd(targetLength ...

  8. 工作簿(Workbook)基本操作应用示例

    Workbook对象代表工作簿,而Workbooks集合则包含了当前所有的工作簿.下面对Workbook对象的重要的方法和属性以及其它一些可能涉及到的方法和属性进行示例介绍,同时,后面的示例也深入介绍 ...

  9. C#如何设置Excel文档保护——工作簿、工作表、单元格

    简介 Excel在工作和学习中应用广泛,是必不可少的数据统计与处理工具.对于一些重要的Excel文件,只供特殊人员查看.编辑或者防止重要数据对外泄露时,就需要设置文档保护,包括设置访问密码.设置文件只 ...

最新文章

  1. ==和equals的浅析
  2. Graves of the Internet - 互联网坟墓
  3. JAVA框架Struts2
  4. mac打开class文件
  5. 使用ENTER模拟触发表单提交或者click事件
  6. 发光强度/光通量/光照度/亮度/坎德拉/流明/勒克斯/尼特之间的关系和换算
  7. Java线程池 / Executor / Callable / Future
  8. linux 上传网页文件大小,Linux:上传未完成的文件 – 文件大小检查(scp / rsync)
  9. php用空格分隔的字符串对比,探讨各种PHP字符串函数的总结分析
  10. LY.JAVA面向对象编程.内存图
  11. 1988-2020年各省、分城乡基尼系数、基尼系数计算及相关经典文献、1978-2019年中国省市恩格尔系数表、泰尔指数计算模板、208个地级市和31个省、市城乡泰尔指数
  12. win7(32bit)下完整的搭建apache(2.2.x)+openssl(0.9.6-1.0.1升级)过程
  13. 【项目】用户可自定义简易宏键盘
  14. 极客日报:HarmonyOS 2.0用户数升至5000万;腾讯起诉抖音侵权《王者荣耀》,获赔60万?抖音:没侵权,已上诉!
  15. MySQL语法添加多个外码约束
  16. echarts世界地图
  17. Tekton笔记(四)之Authentication及catalog skopeo
  18. JS 数组,对象。中划线、数字属性时值获取
  19. 手机邮箱看不到已发送邮件_iPhone用户请注意:你的邮件App得禁用,刚曝光的安全漏洞,iOS 6以上设备全中招...
  20. 国际标准化组织(Iso)对质量(Quality)的定义

热门文章

  1. 计时器(视频的计时:时间码)
  2. Compose - 主题 Theme
  3. php支付宝授权回调地址,#支付宝 应用网关和授权回调地址怎么配置?
  4. Linux Audio (6) DAPM-3 damp的kcontrol注册过程
  5. 机器学习-白板推导-系列(十)笔记:EM算法
  6. 在linux中运行c语言程序,linux环境中运行C语言程序
  7. Restful API 的接口规范
  8. ajax对数据进行封装,ajax封装
  9. 最小二乘法求拟合曲线函数的C语言实际应用
  10. 银行理财计算复利的功能实现。