我有一个看起来像这样的列表:
{1: "a", 2: "a", 3: "c", 4: "c"}
我想检查该列表中是否有“c”。这是我的代码的一部分:
answer= {1: "a", 2: "a", 3: "c", 4: "c"}
answer[indexString as keyof typeof answer] = value;
if ("c" in answer) {
console.log("true");
}
我不知道为什么它只检查 id 1,2,3,4 值而不检查字符串 "a","b", "c" .如果有人可以帮助我,真的很感激
答案 0 :(得分:2)
你拥有的是一个对象,而不是一个列表。要检查对象的值中是否存在某个值,请使用创建值列表的 Object.values
函数。然后检查其中是否存在需要值: Object.values(answer).includes("c")
答案 1 :(得分:2)
您需要检查对象中是否存在某个值。您可以执行以下操作,
answer= {1: "a", 2: "a", 3: "c", 4: "c"};
if(Object.values(answer).includes("c")){
console.log("true");
}
答案 2 :(得分:1)
您是否尝试使用
<块引用>Object.values(answer).includes("c");