2014-09-29 82 views
1

定义的数组大小和克隆这是我下面的代码:的JavaScript从另一个阵列

customQuestionnaire['questions'] = customQuestionnaire['questions'].slice(0,numberOfQuestions); 

我要输出numberOfQuestions数组大小,但复制高达numberOfQuestions阵列上。如果数组以前更大,这将起作用。但是,如果数组以前更小,我想声明一个更大的数组(其余部分是'undefined')呢?我应该这样做吗?或者上面的代码就足够了。

var temp = customQuestionnaire['questions'].slice(0,numberOfQuestions); 
customQuestionnaire['questions'] = new Array(numberOfQuestions); 
customQuestionnaire['questions'] = temp.slice(); 

但是看起来和前面的代码一样。我应该怎么做呢?谢谢。

回答

0

我会建议填充数组的其余部分,直到具有未定义值的所需长度。例如:

var numberOfQuestions = 10; 
var arr = [1,2,3,4,5]; 
var result = arr.slice(0,numberOfQuestions); 

if(numberOfQuestions > arr.length){ 
    var interations = numberOfQuestions - arr.length; 
    for(var i =0; i< interations; i++){ 
     result.push(undefined); 
    } 
} 
console.log(result); 

这个例子的输出是:

[1, 2, 3, 4, 5, undefined, undefined, undefined, undefined, undefined] 

所以你有numberOfQuestions的长度的新数组。复制现有值,如果尝试使用未定义的值,您将得到错误

0

使用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