Код, который использует temp
var, не будет отличаться от вашего исходного кода.
// This creates a copy of the array stored in customQuestionnaire['questions']
// and stores it in temp
var temp = customQuestionnaire['questions'].slice(0,numberOfQuestions);
// this creates a new empty array with a length of numberOfQuestions and
// stores it in customQuestionnaire['questions']
customQuestionnaire['questions'] = new Array(numberOfQuestions);
// this creates a copy of the array stored in temp (itself a copy) and
// immediately overwrites the array created in the last step with this copy of
// the array we created in the first step.
customQuestionnaire['questions'] = temp.slice();
Использование .slice
создает копию массива вы вызываете метод, но так как вы сразу перезапись массива, я предполагаю, что вам не нужно, чтобы сохранить исходное значение customQuestionnaire['questions']
.
Самый простой (и, вероятно, самый эффективный) способ выполнить то, что вы хотите, - просто отрегулировать .length
property массива.
customQuestionnaire['questions'].length = numberOfQuestions;
Если numberOfQuestions
короче, чем длина массива это усечь массив numberOfQuestions
вопросов. Если numberOfQuestions
длиннее массива, массив будет мутировать в массив, содержащий numberOfQuestions
элементов, элементы, выходящие за пределы исходного массива, будут undefined
по вашему желанию.
Если вам нужно скопировать исходный массив, вы можете все еще использовать .slice
, чтобы сделать это:
var questionnaire = customQuestionnaire['questions'].slice();
questionnaire.length = numberOfQuestions;
// do something with questionnaire