Javascript 中的切片方法索引问题

Slice method indexing issue in Javascript

我有一个字符串作为表单的输入;让我们说“1,5; 6,10”。现在,我想比较位置 1 和 3 的数字,即(1 和 6)。无论哪个最大,都会打印出它的数字。在这种情况下,数字 10 将打印为 1 < 6.

假设输入是, const customer_demand ="1,5;6,10";

我想用 slice() 方法处理并用以下方法分隔 1 和 6:

const number1 = customer_demand.slice(0, 1); // 1

const number2 = customer_demand.slice(4, 5); // 6

并将结果与​​ if & else 进行比较。但是可能会有第三个数字是两位数的情况,例如:

const customer_demand ="1,5;16,10";

我的 slice() 方法索引会偏移。在这方面我能做什么?我希望我已经说清楚了,如果没有请发表评论。谢谢

在你的情况下,最好使用 split:

const customer_demand ="1,5;16,10";

const number1 = customer_demand.split(";")[0].split(",")[0]; // 1

const number2 = customer_demand.split(";")[1].split(",")[0]; // 16

此外,如果您希望它们成为 Numbers,请不要忘记使用 parseInt.

进行转换

解决方法,使用split。这是一个例子

const customer_demand ="1,5;16,10";
function parseNumbers(string){
  return string.split(";") //returns stuff like ["1,5", "16,10"]
  .map(axis=>
    axis.split(",") //["1", "5"]
    .map(n=>parseInt(n)) //[1,5]
  )
}

//example usage
const parsedDemand=parseNumbers(customer_demand)
const [number1,number2,number3,number4]=parsedDemand
console.log(parsedDemand)

让您的生活更轻松,并将您的字符串分解为易于管理的数组。这是您不知道要提前比较多少组数字的示例。

const customer_demand ="1,5;16,10";
// the following should also work for data like: "1,3,4,7;1,44;100"
let answers = [];
customer_demand.split(";").forEach( set => {
  let setitems = set.split(",");
  let biggest = setitems.reduce(function(a, b) {
    return Math.max(Number(a), Number(b));
  });
 answers.push(biggest)
});
// answers is now an array - each item is the biggest number of that set. In your example it would be [5,16]