给定两个数字,返回一个长度为num1的数组,每个值为nu

时间:2018-06-11 07:01:43

标签: javascript arrays

我正在学习如何编码,并且我坚持参加本练习:给定两个数字,返回一个长度为num1且每个值为num2的数组。打印" Jinx!"如果它们是相同的。

以下是我现在的代码:

function thisLengthThatValue(num1,num2) {

    if (num1 == num2) {
        console.log("Jinx!");
    }

    var newArray = [];
    var len = 0;

    while (len <= num1) {
        newArray.push(num2);
        len++;
    }
}

3 个答案:

答案 0 :(得分:0)

你需要检查小于或小于等于,因为你从零开始,而不是一个循环。

len < num1

然后,如果值

,则需要退出函数并返回所需的字符串
num1 === num2

是平等的。

function thisLengthThatValue(num1, num2) {

    if (num1 === num2) {      // taken an identity check ===
        return "Jinx!"        // exit function with the value
    }

    var newArray = [];
    var len = 0;

    while (len < num1) {
        newArray.push(num2);
        len++;
    }
    return newArray;
}

console.log(thisLengthThatValue(3, 3));
console.log(thisLengthThatValue(1, 3));
console.log(thisLengthThatValue(3, 1));

答案 1 :(得分:0)

您需要从缺少的函数返回newArray

function thisLengthThatValue(num1,num2) {
  if (num1 == num2) {
    return "Jinx!";
  }
  var newArray = [];
  var len = 0;
  while (len < num1) {
    newArray.push(num2);
    len++;
  }
  return newArray;
}

var res = thisLengthThatValue(5,2);
console.log(res);
res = thisLengthThatValue(5,5);
console.log(res);

答案 2 :(得分:0)

function thisLengthThatValue(num1,num2) {

    if (num1 == num2) {
        console.log("Jinx!");
    }

    var newArray = [];
    var len = 0;

    while (len < num1) { // strict inequality
        newArray.push(num2);
        len++;
    }

    return newArray;
}

您正在检查数组长度是否较低或等于到所需长度,如果为true,则添加新元素。