【问题标题】:Slice method indexing issue in JavascriptJavascript中的切片方法索引问题
【发布时间】:2021-05-05 21:16:41
【问题描述】:

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

让输入是, 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() 方法索引会偏移。在这方面我能做些什么?我希望我已经说清楚了,如果没有,请发表评论。谢谢

【问题讨论】:

  • 你的输入字符串有不同的分隔符吗? “,”,“;”,还有什么?
  • @DmytroKrasnikov 是的,它就像“a,b;c,d”

标签: javascript slice


【解决方案1】:

在您的情况下,最好使用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 进行投射。

【讨论】:

  • 谢谢@Dmitry,我之前也考虑过使用Split()。但是我应该在最大数字的右边打印数字吗?
  • @KamranShakeel 我不明白你想要什么。请澄清您的评论。
  • 谢谢你,我想通了。。谢谢你的帮助!!
【解决方案2】:

解决方案,使用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)

【讨论】:

    【解决方案3】:

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

    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2021-12-31
      • 2018-07-29
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多