2016-08-16 45 views
-1

我有这个功能,我想重新排列数组中最后找到的所有0,我正在使用一个临时数组。一切都很好,直到我检查了testArray这是作为参数收到的原始数组的长度。为什么我找不到他的长度以及第一个for如果他的长度未定义如何工作?无法获得作为参数收到的数组的长度

window.onload = function() { 
 

 
var testArray =[5,3,0,55,0,9,0,8]; 
 
function moveArray(testArray){ 
 
    var tempArray= []; 
 
    console.log(tempArray.length + " vs " + testArray.lenght); 
 
    for(var i = 0 ;i < testArray.length; i++) { 
 
    if(testArray[i] != 0){ 
 
     tempArray.push(testArray[i]); 
 
    // console.log("pushed " + testArray[i]); 
 
    } 
 
    } 
 
// console.log(tempArray.length + " vs " + testArray.lenght); 
 
    while(tempArray.length < testArray.lenght){ 
 
     tempArray.push('0'); 
 
    // console.log('push 0'); 
 
    } 
 
    testArray=tempArray; 
 
    for(var i = 0 ;i < testArray.length; i++){ 
 
    // console.log(testArray[i]); 
 
    } 
 
}; 
 
    
 
    moveArray(testArray); 
 
    };

+0

你只是想移动的0到最后还是你也想的其余值排序? – charsi

+6

'lenght' **长度** –

+0

testArray.lenght?它应该是testArray.length – Oxi

回答

2

你正在使用错误拼写在这些线路

while(tempArray.length < testArray.lenght){ 

console.log(tempArray.length + " vs " + testArray.lenght); 

应该

while(tempArray.length < testArray.length){ 

console.log(tempArray.length + " vs " + testArray.length); 
0

,首先你有一个错字与你的 “长度” ,长度应该是长度。其次,你可能想要回报你的价值。

这里是一个工作示例:

window.onload = function() { 

var testArray =[5,3,0,55,0,9,0,8]; 

function moveArray(testArray){ 
    var tempArray= []; 
    for(var i = 0 ;i < testArray.length; i++) { 
     if(testArray[i] != 0){ 
      tempArray.push(testArray[i]); 
     } 
    } 

    while(tempArray.length < testArray.length){ 
     tempArray.push(0); 
    } 
    return tempArray; 
}; 

console.log(testArray); // output: [5, 3, 0, 55, 0, 9, 0, 8] 
testArray = moveArray(testArray); 
console.log(testArray); // output: [5, 3, 55, 9, 8, 0, 0, 0] 
}; 
相关问题