【发布时间】: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