如何将字符串提示输入保存到数组中

时间:2018-11-02 16:16:35

标签: javascript arrays prompt

感谢大家的努力。一切正常。

2 个答案:

答案 0 :(得分:1)

这里是一个例子。

这将使用给定的两个数字,并从最小到最大填充数组。

之后,您可以决定如何处理数组。

let arr = [];                    //create array

let numOne = validateNumber();
let numTwo = validateNumber();
createArray(numOne, numTwo);     // call function to populate array

arr.forEach(number => {
  console.log(number);
})              


function validateNumber(){
  let pass = false;
  let number = 0;
  while (!pass){
    number = parseInt(prompt('Enter a number'));
    if (Number.isInteger(number)) pass = true;
  }
  return number;

}

function createArray(numOne, numTwo){
  var start = numOne;
  var end = numTwo;

  if (numOne > numTwo){
    start = numTwo;
    end = numOne;
  }
  for (var i = start; i <= end; i++) {
    arr.push(i)
  }
}

答案 1 :(得分:0)

您可以创建以下功能来开始使用。

function returnRange(start, end) {
    //Array to store numbers in.
    var myarray = [];

    // Check if the provided parameters are numbers and return an error message if they are.
    // Else add the range of numbers to the array
    if (isNaN(start) || isNaN(end)) {
        console.log("One of these is not a number:");
        console.log("start = " + start + " end = " + end);
    } else {
        //Loop through your input and store into an array
        for (var i = start; i < end + 1; i++) {
            myarray.push(i);
        }

        // You can use console.log(myarray) here to verify it is returning the correct range
        return myarray;
    }
}

returnRange(1,5);