javascript - 如何在 Javascript 中正确使用 if 语句中的数组
问题描述
我有一个非常基本的问题。对此感到抱歉。我正在尝试构建结果点系统进行测试。但是有一个问题是所有东西都打印在一起。有一个代码:
var g_Point = [8,9,10];
var n_Point = [5,6,7];
var b_Point = [1,2,3,4];
var my_Points = 10;
if(my_Points === g_Point){
document.write('You Got Really Good Point');
}else if(my_Points === n_Point){
document.write('You Got Normal Points');
}else if(my_Points === b_Point){
document.write('You Got Really Bad Points');
}
解决方案
您不是在比较两个值,而是要检查一个值是否包含在数组中,然后使用Array.prototype.includes()
:
var g_Point = [8, 9, 10];
var n_Point = [5, 6, 7];
var b_Point = [1, 2, 3, 4];
var my_Points = 10;
if (g_Point.includes(my_Points)) {
document.write('You Got Really Good Point');
} else if (n_Point.includes(my_Points)) {
document.write('You Got Normal Points');
} else if (b_Point.includes(my_Points)) {
document.write('You Got Really Bad Points');
}
推荐阅读
- browser - 如何在 Google Chrome 等浏览器中打开 CasperJS/PhantomJS 文件?
- makefile - makefile 有一个通用目标,它也是默认目标
- woocommerce - 如何在woocommerce中获取特定类别的所有产品?
- azure - 使用 Azure AD B2C 自定义策略为本地帐户签名时用户名或密码无效
- java - 写入时由 onDrawFrame 读取的数组
- sql - 获取总计:我如何从本准则中按性别或身体获取各省的女性/男性总计?
- sas - SAS 将每月增量数据集附加到一个数据集中
- powershell - ConvertFrom-String 返回无法以表格形式查看的 System.Array
- go - 当请求被取消或超时时如何从 http 处理程序返回
- graphql - github graphql api,“clientMutationId”是什么意思?