如何将js数组值与字符串进行比较

时间:2020-11-11 18:48:55

标签: javascript

我有一个JSON数组,我想将其值与String进行比较。例如,我的JSON数组是

{
  "slot": ["10:00 AM", "10:30 AM", "03:30 PM"]
}

现在我正尝试以这种方式访问​​它:

for (i in data.slot) {
  console.log(slot[i] === "10:00 AM"); //this return false
  if (slot[i] === "10:00 AM") btn1.disabled = true;
  if (slot[i] === "10:30 AM") btn2.disabled = true;
  if (slot[i] === "03:00 PM") btn3.disabled = true;
  if (slot[i] === "03:30 PM") btn4.disabled = true;
}

现在,每当我尝试进行比较时,if语句都将返回false,并且不会禁用该按钮。我是在Chrome开发者控制台上了解这一点的。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:4)

您需要解决正确的变量

data.slot[i]
^^^^^

const data = { slot: ["10:00 AM", "10:30 AM", "03:30 PM"] }

for (let i in data.slot) {
  console.log(data.slot[i] === "10:00 AM"); // true false false
  if (data.slot[i] === "10:00 AM")
    btn1.disabled = true;
  if (data.slot[i] === "10:30 AM")
    btn2.disabled = true;
  if (data.slot[i] === "03:00 PM")
    btn3.disabled = true;
  if (data.slot[i] === "03:30 PM")
    btn4.disabled = true;
}
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
<button id="btn4">4</button>

更好的方法是通过迭代for ... of statement

直接获取价值

const data = { slot: ["10:00 AM", "10:30 AM", "03:30 PM"] }

for (const value of data.slot) {
    console.log(value === "10:00 AM"); // true false false
    if (value === "10:00 AM") btn1.disabled = true;
    if (value === "10:30 AM") btn2.disabled = true;
    if (value === "03:00 PM") btn3.disabled = true;
    if (value === "03:30 PM") btn4.disabled = true;
}
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
<button id="btn4">4</button>

答案 1 :(得分:0)

const data = {
  slot: ["10:00 AM", "10:30 AM", "03:30 PM"],
};

for (i in data.slot) {
  const _slot = data.slot[i];
  console.log(_slot === "10:00 AM");
  if (_slot === "10:00 AM") btn1.disabled = true;
  if (_slot === "10:30 AM") btn2.disabled = true;
  if (_slot === "03:00 PM") btn3.disabled = true;
  if (_slot === "03:30 PM") btn4.disabled = true;
}