首页 > 解决方案 > 如何在 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');
    }

标签: javascript

解决方案


您不是在比较两个值,而是要检查一个值是否包含在数组中,然后使用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');
}


推荐阅读