javascript - 如何为数组中的特定数值返回真或假?
问题描述
一个数组有多个数值,我需要找到中间为零的那个才能返回真。
对于我的输出,我得到:
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');
解决方案
您可以使用“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));
推荐阅读
- jmeter - 了解 Jmeters 线程组持续时间
- flutter-animation - 颤动动画显示列表项的移动
- javascript - 如何将 adobe leonardo 输出的对象数组转换为更简单的对象以进行顺风配置
- metal - Metal 得到一个断言,断言失败`sourceLevel(1) must be < [sourceTexture mipmapLevelCount](1)。(lldb)
- eclipse - 当我尝试从 Eclipse Marketplace 将 e(fx)clipse 下载到我的 Eclipse IDE 中时,如何解决此错误?
- bash - 如何重命名终端上的所有目录
- javascript - 全局存储来自服务器的数据
- python - str[0:z] 适用于 pandas 但不适用于 modin:TypeError: 'StringMethods' object is not subscriptable
- javascript - 如何在 Google 脚本的自定义“whenFormulaSatisfued”函数中传递范围对象?
- ruby - 如何通过读取 Ruby 中的文本文件来创建哈希?