【问题标题】:How to print just a single integer inside a for loop not the entire array's result in javascript?如何在for循环中只打印一个整数而不是整个数组在javascript中的结果?
【发布时间】:2021-07-15 16:38:36
【问题描述】:

这是我要解决的问题:

给定一个数字 n 后跟 n 个数字,打印大于 15 的数字,如果不存在数字,则打印 -1。

输入说明: 0

输出说明: 如果不存在数字,则打印大于 15 的数字 print -1

示例输入:

3
5 7 4

样本输出:

-1

我正在尝试这样解决它:

var n = 3
var nums = [5, 7, 4]
for (var i of nums){
    if (i > 15) {
        console.log(i)
     } else{
        console.log(-1)
    }
}

但是我得到了这个输出:

-1
-1
24

如果没有大于15 的数字,我只想打印24-1,请问我可以详细说明一下吗?

【问题讨论】:

  • 已经有了答案,我只是想建议你应该使用let 而不是var

标签: javascript arrays for-loop


【解决方案1】:

使用 for 循环检查每个数字,一旦发现情况满足就使用break 语句。

 var n = 3
 var nums = [5, 7, 4, 24]
 // Let the end answer be -1
 let result = -1
 for (var i of nums) {
   if (i > 15) {
     // If the situation is satisfied, set the result and end the for loop.
     result = i
     break;
   } else {
     result = -1
   }
 }
 // At the end log the answer.
 console.log(result)

【讨论】:

【解决方案2】:

您在for 循环中运行的内容与 for 循环作为一个整体运行的次数一样多。因为这是homework answer,所以我不会直接回答你,而是想想你的代码现在在做什么,你的if 块在每次for循环运行时都在运行。

一些提示:

  1. for 循环运行了多少次?
  2. 鉴于这个答案,您通常如何运行一次?
  3. 如何在循环中完成工作,然后在循环外进行工作?
  4. 记住您的布尔运算符。 true 最初是 false 和满足条件后的 true,你如何保留它?

【讨论】:

    【解决方案3】:

    您可以为此使用Array.find。如果使用循环,则立即返回找到的值,如果没有找到(循环完成后),则返回 -1。两种解决方案请参见 sn-p。

    const n = 3;
    const nums = [5, 7, 4];
    const findValueInArrayGreaterThen = (arr, value) => arr.find(v => v > 15) || -1;
    
    nums.unshift(3); // a number n followed by n numbers...
    
    console.log(`nums: ${JSON.stringify(nums)}; findValueInArrayGreaterThen(nums, 15): ${
      findValueInArrayGreaterThen(nums, 15)}`);
    
    nums.push(15.1);
    console.log(`nums: ${JSON.stringify(nums)}; findValueInArrayGreaterThen(nums, 15): ${
      findValueInArrayGreaterThen(nums, 15)}`);
    
    nums.pop();
    console.log(`nums: ${JSON.stringify(nums)}; findValueInArrayGreaterThenLoop(nums, 15): ${
      findValueInArrayGreaterThenLoop(nums, 15)}`);
    
    function findValueInArrayGreaterThenLoop(arr, value) {
      for (let value of nums) {
        if (value > 15) {
          return value;
        }
      }
      return -1;
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      相关资源
      最近更新 更多