首页
学习
活动
专区
工具
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
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52105459

复制
相关文章

相似问题

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