大家好,又见面了,我是你们的朋友全栈君。
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
语句的负载。 这种神奇的方法把我甩了下来。 我简直不敢相信它的存在。
Mozilla Developer Network (MDN) Docs:
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
不会执行任何操作。
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。
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行。我们看到targetLength
和padString
进入了我们的函数。 还没有疯狂,但它来了。 我一直在避开5号线足够长时间。
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:
这是做什么的:
a
is converted into binary (details here).
a
转换为二进制( 此处有详细信息 )。
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”开关true
和false
。 true
的二进制形式为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
。
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
。 我们实际上并不想转移任何东西,因为那会改变价值。
Jump to line 7’s debugger
now. targetLength
has been sanitized. Next!
现在跳到第7行的debugger
。 targetLength
已targetLength
。 下一个!
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
语句,因为targetLength
和padString.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文件 :
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
与原始字符串的组合,就完成了!
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文件 :
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/
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/195544.html原文链接:https://javaforall.cn