我正在做一个简单的问答游戏,在计算结果时遇到了一些麻烦。问题非常简单,我需要找出如何说clicked1
的值是否比整个字典中的值大,然后执行此功能。这是字典和我要制作的函数的代码。另外,如果有人可以解释为什么possibilities.value
不能解决我的问题,将不胜感激。
var possibilities = {
'clicked1': 0,
'clicked2': 0,
'clicked3': 0,
'clicked4': 0,
};
function results(){
if (possibilities['clicked1'] > possibilities){
console.log("it worked");
}
};
答案 0 :(得分:1)
只需使用Object.values
遍历every
:
var possibilities = {
'clicked1': 0,
'clicked2': 0,
'clicked3': 0,
'clicked4': 0,
};
if (Object.values(possibilities).every(val => possibilities.clicked1 >= val || val == possibilities.clicked1)) {
console.log("It works!");
}
答案 1 :(得分:0)
您可以使用every()
。您还可以使用Math.max()
和Rest参数
var ps = {
'clicked1': 4,
'clicked2': 1,
'clicked3': 2,
'clicked4': 3,
};
if(Object.keys(ps).every(key => ps[key] <= ps.clicked1)){
console.log("worked")
}
//Second Method:
//Object.values(ps) will return '[4,1,2,3]' And then using ... all values
//are passed to function Math.max() single argument. and it will return the max value out of those and then compare that value with you desired value
if(Math.max(...Object.values(ps)) === ps.clicked1){
console.log("Worked");
}
答案 2 :(得分:0)
这里的方法与您尝试的方法非常相似。
基本上遍历字典中的键和值,而忽略键'clicked1'的值:
let possibilities = {
'clicked1': 0,
'clicked2': 0,
'clicked3': 0,
'clicked4': 0,
};
function result() {
for (let key in possibilities) {
if (key !== 'clicked1' && possibilities[key] >= possibilities['clicked1']) {
return "it did not work";
}
}
return "it worked";
}
console.log(possibilities);
console.log("result() =", result());
possibilities['clicked1'] = 1;
console.log(possibilities);
console.log("result() =", result());
答案 3 :(得分:0)
另一种替代方法是检查是否发现某个元素大于possibilities["clicked1"]
。如果找到一个,您将知道possibilities["clicked1"]
不是最大值,否则它将是最大值。对于此方法,我们可以使用Object.values()从您的对象中获取值的数组,然后我们使用Array.some()进行上述验证:
var possibilities1 = {'clicked1': 6, 'clicked2': 3, 'clicked3': 4, 'clicked4': 5};
var possibilities2 = {'clicked1': 3, 'clicked2': 3, 'clicked3': 4, 'clicked4': 5};
function results(ps)
{
let found = Object.values(ps).some(x => x > ps['clicked1']);
found ? console.log("not worked") : console.log("worked");
};
results(possibilities1);
results(possibilities2);