Есть ли способ иметь более одного входа в функцию после ее написания? - PullRequest
0 голосов
/ 13 апреля 2020

Я довольно новичок в этом и пытаюсь узнать больше об использовании массивов в Javascript. Я делал некоторые функции, в которых я брал бы массив, новый ввод и вставлял его в функцию, подобную:

function printArray(array){
    //This function will print out each of the entries of the array 
    console.log("This is the Output from the Print Array Function: ")
    console.time()
    let arr = array;
    for(let index = 0; index < arr.length; index++){
        console.log(arr[index]);
        //This is the function
    }
    console.timeEnd();
}

Это хорошо, если использовать только один аргумент в функции: но когда я попытался сделать что-то похожее с array.push(), исходный синтаксис: array.prototype.push(input1 --> InputN) I предположим, что это мой вопрос, как я могу воспроизвести в аргументах функции, что это может быть либо один вход, либо несколько входов. Вот что я сделал вместо этого:

function singlePushArray(array,input){
    //This function ADDS ONE ITEM to the END OF THE ARRAY
    console.time();
    console.log("This is the Output from the Single Push Array Function- Adding a Single Items to the END of the ARRAY")
    console.log("This is the Original Copy of the Array: ", array);
    array.push(input);//This is the function
    console.log("This is the Ammended Cop of the Array: ", array);
    console.timeEnd();
    
}

function doublePushArray(array,input1,input2){
    //This function ADDS TWO Items to the END OF THE ARRAY

    console.time();
    console.log("This is the Output from the Double Push Array Function - Adding TWO Items to the END OF THE ARRAY");
    console.log("This is the Original Copy of the Array: ", array);
    array.push(input1,input2);//This is the function
    console.log("This is the ammended Copy of the Array: ", array);
    console.timeEnd()
}

(прошу прощения за излишний консольный лог и временные метки. Я просто использую его в качестве учебного пособия. Если кто-нибудь может мне помочь, это будет очень признательно. Большое спасибо =)

1 Ответ

1 голос
/ 13 апреля 2020

Вы можете использовать параметр отдыха с ...:

function nPushArray(array, ...inputs) {
  //This function ADDS N ITEMS to the END OF THE ARRAY
  console.time();
  console.log("This is the Output from the n Push Array Function- Adding N Items to the END of the ARRAY")
  console.log("This is the Original Copy of the Array: ", array);
  array.push(...inputs); //This is the function
  console.log("This is the Ammended Cop of the Array: ", array);
  console.timeEnd();
}

//usage
nPushArray([1, 2, 3], 4, 5);
nPushArray([1, 2, 3], 4, 5, 6, 7, 8)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...