2012-10-26 152 views
0

嗨我正在使用ajax調用一個名爲build_Array的函數。這個函數應該分解myString,它是「致電1-877-968-7762開始你的假期,1,0,通過;你有資格獲得50%的工資,1,365,通過;你的假期將是無償的。 1,0,後;」 分成多個部分,並用逗號分隔成2d數組。但它不起作用。它說數組的所有值都是未定義的。這裏就是我所說的AJAX內部功能...(它的工作原理中的jsfiddle http://jsfiddle.net/ChaZz/3/AJAX/JavaScript功能不起作用

var request = new XMLHttpRequest(); 
    request.onreadystatechange = function() { 
    if (request.readyState == 4 && request.status == 200) { 
     var myString = request.responseText; 
     myString = build_Array(myString); 
     document.getElementById('ajax').innerHTML = myString; 
    } 
    } 

這裏是功能build_Array ...

function build_Array (myString) { 
    var mySplitResult = myString.split(';'); 
    var myArray = new Array(mySplitResult.length); 

    //may need to get rid of -1 
    for(var i = 0; i < mySplitResult.length -1; i++){ 
    myArray[i] = new Array(4); 
    var mySplitResult2 = mySplitResult[i].split(','); 

    for(var z = 0; z < mySplitResult2.length; z++) { 
     myArray[i][z] = mySplitResult2[z]; 
    } 
    } 
    var final_message = myArray[1][1]; 
    return final_message; 
} 

回答

2

​​

var myString = "Call 1-877-968-7762 to initiate your leave.,-30,0,through;You are eligible to receive 50% pay.,0,365,through;Your leave will be unpaid.,365,0,After;"; 

function build_Array (myString) { 
    var mySplitResult = myString.split(';'); 
    var myArray = []; 

    for(var i = 0; i < mySplitResult.length; i++){ 
    myArray[i] = []; 
    var mySplitResult2 = mySplitResult[i].split(','); 

    for(var z = 0; z < mySplitResult2.length; z++) { 
     myArray[i][z] = mySplitResult2[z]; 
    } 
    } 
    var final_message = myArray[1][1]; 
    return final_message; 
} 

console.log(build_Array(myString)); // 0 
+0

console.log做什麼? –

+0

它登錄到控制檯... – Shmiddty

+0

每個現代瀏覽器中的開發者控制檯。 – Shmiddty

0

不需要將循環從mySplitArray2複製到myArray,只需將由split返回的數組直接分配給新數組的該元素。並且array.push可用於逐步構建陣列。

function build_Array (myString) { 
    var myArray = []; 
    for (substring in myString.split(';')){ 
    myArray.push(substring.split(',')); 
    } 
    var final_message = myArray[1][1]; 
    return final_message; 
}