如何解决您如何将类似400..900的内容转换为从400,500,600,700,800,900,1000的数组中过滤值的方法
我是从Google字体API中获得的,因此,如果您提出一种字体要求,那么您希望获得许多粗细,您基本上可以索要400..900。基本上,每种字体的权重都在400到900之间,或者您必须写400,500,600,700,800,900。
我想使用相同的逻辑,可以通过拆分并运行过滤循环来完成。我想知道是否有更好的方法可以做到这一点。那可能更有用和更原生。我不想分裂他们。我很好的解决方案很好奇。
let a = '400..900';
a = a.split('..');
let b = [100,200,300,400,900,1000].filter((x) => (x >= a[0] && x <= a[1]))
console.log(a,b);
// 400,900
解决方法
您可以使用100步的for循环
untagOutwardDetailsDto.DiamondDetails
对于这两个数字之间的任意分隔符,您可以使用regex提取开始和结束
DiamondDescriptionModel
,
说实话,您的做法非常可靠,我会遵循的方式。没有比使用过滤器更好的根本方法。
如果要使其更具可读性,可以将拆分的a
分解为单独的变量。您还会有一些额外的括号。
此外,将值列表移动到可重用的常量而不是每次都重新声明也可以。
const values = [100,200,300,400,500,600,700,800,900,1000];
let a = '400..900';
const [start,end] = a.split('..');
let b = values.filter(x => x >= start && x <= end)
console.log(start,end,b);
但是,所有这些都是非常非常小的和/或仅仅是风格上的变化。
至于不想使用split
,实际上并没有解决办法,也没有理由避免使用它。 split
相当快。另一种选择是使用Regex(^(\d+)\.\.(\d+)$
),但从性能和可读性的角度来看,我绝对会认为这更糟。
否则,如果您知道它们只会为您提供3位数字的值,则可以使用子字符串,但同样,这会降低可读性,如果他们给出1000,则会搞砸。
,您可以像这样更动态地进行操作
const input = '400..900';
const bounds = input.split('..').map(x => parseInt(x));
const getAllInbetween = (bounds,stepSize) => {
const steps = (bounds[1] - bounds[0]) / stepSize + 1; // Calculate how many steps are needed between the bounds
return new Array(steps) // Create an array with the size of the amount of steps
.fill(0) // Fill it with zeroes
.map((_,i) => i * stepSize + bounds[0]) // loop over it and assign the values,using the current array index
}
console.log(getAllInbetween(bounds,100));
,
这是使用正则表达式的更严格的方法。
不一定是更好的性能,但我相信它会更强大/更适合您的目的。
const query = '400..600';
const sizes = [400,1000];
const match = /^(([4-9]|10)00)\.\.(([4-9]|10)00)$/.exec(query);
if (!match) {
throw "Invalid input string"
}
const offset = sizes[0]/100;
console.log(sizes.slice(+match[2] - offset,+match[4] + 1 - offset));
,
我的版本
const a = '400..900';
const [from,to] = a.split('..');
const b = Array(Math.ceil((to - from + 100)/100)).fill().map((_,i) => (+from + (i*100)))
console.log(b)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。