javascript - 在Javascript中使用indexOf将变量类型号与数组进行比较
问题描述
我已将click
事件侦听器添加到按钮。它调用按钮YES
AND NO
。基本上indexOf
检查变量中的值foto
是在yesMeetup
数组中还是在notMeetup
数组中。
我试图调试,但我总是得到“你知道了”,当我点击NO
按钮时它没有调用调试器
let foto = Math.floor(Math.random() * 20) + 1;
document.querySelector('.btn').addEventListener('click', verify);
function verify() {
var yesMeetup = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15];
var notMeetup = [16, 17, 18, 19, 20];
var notButton = document.getElementById('no');
var yesButton = document.getElementById('yes');
var decisao = document.getElementById('decisao');
debugger;
if (yesButton) {
if (yesMeetup.indexOf(foto)) {
decisao.textContent = "You got it";
} else if (notMeetup.indexOf(foto)) {
decisao.textContent = "wrong";
}
} else if (notButton) {
if (notMeetup.indexOf(foto)) {
decisao.textContent = "You Gou it";
} else if (yesMeetup.indexOf(foto)) {
decisao.textContent = "Wrong";
}
}
}
解决方案
语句将评估传递给它的if
任何东西作为布尔值。
它不会执行“真”分支的唯一值都是假值:0
, null
, undefined
, ''
, false
, NaN
。
Array.prototype.indexOf
-1
当数组中不存在元素时返回,这不是虚假值之一,因此您的if
条件
if (array.indexOf(element))
将始终评估为真。
var example = [1,2,3];
if (example.indexOf(4)) {
console.log('still true');
}
您可以使用直接比较-1
:
var example = [1,2,3];
if (example.indexOf(4) !== -1) {
console.log('this is not logged');
}
或者更新的,更清洁的,Array.prototype.includes
:
var example = [1,2,3];
if (example.includes(4)) {
console.log('this is not logged');
}
推荐阅读
- sql - 在火花中订购非常慢
- c - 是否有 argc 和 argv 的替代品
- python - for/else 语句中是否有“elif”等价物
- ruby-on-rails - 兑换 #
好的,所以当@products 数组一切正常
#<ActiveRecord::AssociationRelation
时,我在破坏我的代码时遇到错误#<ActiveRecord::Relation
if param
- javascript - 如何在 Reactjs 中将输入值传递给贝宝金额的值?
- c# - 多结构题
- google-cloud-platform - 限制访问我的后端的困难
- postgresql - 使用“psql”时更改默认角色
- javascript - 如何在 SPFx 中使用 MS Fabric UI 制作响应块?
- linux - 如何使用 Bash 脚本将文件随机分布在 3 个文件夹中?