【问题标题】:String Comparison Javascript字符串比较 Javascript
【发布时间】:2020-07-21 11:14:03
【问题描述】:

我刚开始使用 javascript,但在 React 中成功比较两个字符串时遇到了困难(或者在这种情况下只是 Javascript)。假设我有以下功能:

function compare(a, b) {
  var n = -1, m = 0;
  console.log(a, b, b === "important");    // prints here

  if (a === "important") {n = 2;}
  else if (a === "normal") {n = 1;}
  else {n = 0;}

  if (b === "important") {m = 2;}
  else if (b === "normal") {m = 1;}
  else {m = 0;}

  return n - m;
}

但代码的输出(两次单独执行后)是

["normal"]
["important"]    // this case? b is "important"
false
["unimportant"]
["normal"]
false

我不明白为什么上面的代码不起作用。谁能解释一下?提前致谢。

编辑

函数调用

sorter: (a, b) => compare(a.levels, b.levels),

a 和 b 在哪里

  {
    key: "1",
    title: "Eat",
    date: "2020-07-20 07:57",
    levels: ["important"]
  },
  {
    key: "2",
    title: "Sleep",
    date: "2020-07-20 07:57",
    levels: ["normal"]
  },

请注意,该函数是在 React 中调用的。 CodeSandbox Demo

【问题讨论】:

  • 你是怎么调用这个函数的?
  • 根据您的更新:您正在比较数组而不是字符串。

标签: javascript reactjs string comparison


【解决方案1】:

很明显,因为 a 和 b 是数组而不是字符串字面量。您应该在方法中比较 a[0] 或在 compare 方法中传入 a.levels[0]。

【讨论】:

  • 搞砸了,谢谢!没有注意到我将数据作为列表传递。 (8分钟后接受)
【解决方案2】:

你可以使用switch语句

function compare (a, b){
  function swit(v){
      switch (v){
        case 'important' :
          return 2;
        case 'normal' :
          return 1
          default :
            return 0
      }
  }
  return swit(a) - swit(b);
}
var normal = ["normal"];
var important = ["important"]
console.log(compare(normal[0] , important[0]))
console.log(compare(important[0] , important[0]))
console.log(compare(important[0] , normal[0]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-04
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多