这个JS是做什么的

What does this JS do?

本文关键字:什么 JS 这个      更新时间:2023-09-26
var passwordArray = pwd.replace(/'s+/g, '').split(/'s*/);

我发现上面的代码行是一个相当糟糕的JavaScript文件,我不知道它到底是做什么的。我认为它将字符串拆分为字符数组,类似于PHP的str_split。我是对的吗?如果是,有没有更好的方法?

它会替换密码中的空格,然后将密码拆分为一个字符数组。

将字符串转换为字符数组有点多余,因为您已经可以通过括号(..)访问字符串中的字符。()或通过字符串方法"charAt":

var a = "abcdefg";
alert(a[3]);//"d"
alert(a.charAt(1));//"b"  

与:pwd.split(/'s*/)相同。

pwd.replace(/'s+/g, '').split(/'s*/)删除所有空白(tab, space, lfcr等)并将剩余部分(replace操作返回的字符串)拆分为一个字符数组。split(/'s*/)部分是奇怪和过时的,因为在pwd中不应该留下任何空白('s)。

因此pwd.split(/'s*/)应该是足够的。所以:

'hello cruel'nworld't how are you?'.split(/'s*/)
// prints in alert: h,e,l,l,o,c,r,u,e,l,w,o,r,l,d,h,o,w,a,r,e,y,o,u,?

'hello cruel'nworld't how are you?'.replace(/'s+/g, '').split(/'s*/)

replace部分正在从密码中删除所有空白。''s+原子匹配非零长度的空白。'g'部分匹配空白的所有实例,并将它们全部替换为空字符串。