gpt4 book ai didi

Javascript:如何强制 .split() 创建 numArray?

转载 作者:行者123 更新时间:2023-12-02 18:48:29 24 4
gpt4 key购买 nike

这只是一个例子,我有更多的数据:

var str = "3.0;4.5;5.2;6.6";
var res = str.split(";");
console.log(res);

输出将是一个字符串数组。如何获得数字数组而不再次遍历现有数组?

最佳答案

...without going through the existing array again?

这很棘手。您不能使用 split,因为 split 会生成一个字符串数组。您可以使用正则表达式一次性完成此操作,自己构建数组:

var rex = /[^;]+/g;
var str = "3.0;4.5;5.2;6.6";
var match;
var res = [];
while ((match = rex.exec(str)) != null) {
res.push(+match[0]);
}
console.log(res);

或者实际上,这超出了必要的开销,只需 indexOfsubstring 就可以了:

var str = "3.0;4.5;5.2;6.6";
var start = 0, end;
var res = [];
while ((end = str.indexOf(";", start)) !== -1) {
res.push(+str.substring(start, end));
start = end + 1;
}
if (start < str.length) {
res.push(+str.substring(start));
}
console.log(res);

KooiInc's answer使用 replace 为我们执行循环,这很聪明。

<小时/>

也就是说,除非您有一个真正巨大数组,否则再次遍历该数组会更简单:

var res = str.split(";").map(entry => +entry);
<小时/>

在上面,我使用一元 + 将字符串转换为数字。这只是众多方法中的一种,它们各有利弊。我对 this answer 中的选项进行了概述。 .

关于Javascript:如何强制 .split() 创建 numArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53777843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com