首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用于验证数组中的第一项或最后一项是否等于某个数字的函数

用于验证数组中的第一项或最后一项是否等于某个数字的函数
EN

Stack Overflow用户
提问于 2018-08-31 05:15:09
回答 4查看 555关注 0票数 0

我正在尝试编写一个函数来检查数组的第一个或最后一个位置是否包含特定的数字。

那里的所有console.log示例都应该输出true。它的打印方式,我不认为我应该在我的函数中写入console.log。我不能让他们都给true看。

代码语言:javascript
复制
function checkForNumber(arr, num) {
  if (arr[0] === num) {
    //console.log(true) removed
    return true
  } else if (arr.slice(-1)[0] === num) {
    //console.log(true) removed
    return true
  } else
    return false;
}
console.log(checkForNumber([4, 2, 5, 3], 4) === true);
console.log(checkForNumber([4, 2, 5, 3], 3) === true);
console.log(checkForNumber([4, 2, 5, 3], 2) === false);
console.log(checkForNumber([4, 2, 5, 3], 13) === false);

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-08-31 05:29:20

代码语言:javascript
复制
function checkForNumber(arr, num) {
  return arr[0] === num || arr[arr.length - 1] === num;
}
console.log(checkForNumber([4, 2, 5, 3], 4) === true);
console.log(checkForNumber([4, 2, 5, 3], 3) === true);
console.log(checkForNumber([4, 2, 5, 3], 2) === false);
console.log(checkForNumber([4, 2, 5, 3], 13) === false);

if (condition) return true和类似的是反模式。如果函数是谓词(即返回布尔值),则只返回逻辑运算的结果。

票数 5
EN

Stack Overflow用户

发布于 2018-08-31 05:23:21

这是我在评论中建议的完全实现的解决方案。

代码语言:javascript
复制
function checkForNumber(arr, num) {
  if (arr[0] === num || arr[arr.length - 1] === num) {
    return true
  } else
    return false;
}

console.log(checkForNumber([4, 2, 5, 3], 4));
console.log(checkForNumber([4, 2, 5, 3], 3));
console.log(checkForNumber([4, 2, 5, 3], 2));
console.log(checkForNumber([4, 2, 5, 3], 13));
console.log(checkForNumber([4, 2, 5, 4], 4));

票数 1
EN

Stack Overflow用户

发布于 2018-08-31 05:28:24

我觉得这就足够了,对吧?干杯!

代码语言:javascript
复制
function checkForNumber(arr, num)
{
    // for OR
    return ((arr[0] === num) || (arr[arr.length-1] === num));
    // for AND
    // return ((arr[0] === num) && (arr[arr.length-1] === num));
}
console.log(checkForNumber([4, 2, 5, 3], 4) === true);
console.log(checkForNumber([3, 2, 5, 4], 3) === true);
console.log(checkForNumber([0, 4, 4, 8], 2) === false);
console.log(checkForNumber([4, 2, 5, 3], 13) === false);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52105459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档