首页 > 解决方案 > 如何为数组中的特定数值返回真或假?

问题描述

一个数组有多个数值,我需要找到中间为零的那个才能返回真。

对于我的输出,我得到:

false '<-- should be false'
false '<-- should be true'

并且无法弄清楚为什么 true 不会返回 true。

我也试过

if (numbers === 1 && numbers  === 2 && numbers  === 3) {
    doesArrayContainZero = false;
} else if (numbers === 1 && numbers  === 0 && numbers  === 2) {
    doesArrayContainZero = true;
}

认为我可能需要对每个数字更具体,但事实并非如此。

以下是我当前答案的问题。我无法弄清楚为什么它不正确。

function doesArrayContainZero(numbers) {
     if (numbers = [1,2,3]) { return false;} 
     else if (numbers = [1,0,2]) { 
     return true;
     }
}

/* Do not modify code below this line */
console.log(doesArrayContainZero([1, 2, 3]), '<-- should be false');
console.log(doesArrayContainZero([1, 0, 2]), '<-- should be true');

标签: javascript

解决方案


您可以使用“includes”,或者为了与旧浏览器兼容,使用“indexOf”。

var without0 = [1, 2, 3];
var with0 = [1, 0, 2];

function doesArrayContainZero(numbers) {
   return numbers.indexOf(0) !== -1;
}

console.log(doesArrayContainZero(without0));
console.log(doesArrayContainZero(with0));


推荐阅读