Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

有将字符串根据字符转化为数组(不用spilt方法)的方法吗?

如 str = '123|345|567'
我要将这个字符串根据‘|’转化成数组,转化的数组要除去‘|’这个字符,除了split方法还有什么方式吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我在想为什么不用split,这种内置方法效率极高,而且久经考验啊,比你可能的实现(未经考验)好多了。

如果仅仅是讨论算法,则有很多方式,包括上面提到的,此外还可以自己实现,比如利用indexOf之类的查找来实现。
我这里给你一种比较奇怪的实现

let aStr=('123sdf|345sdf sdf |567').replace('|','","');
let aJSONStr='["'+aStr+'"]' ;
let Arr=JSON.parse(aJSONStr);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...