0

Hi I am using an ajax call to a function called build_Array. This function should break up myString which is "Call 1-877-968-7762 to initiate your leave.,1,0,through;You are eligible to receive 50% pay.,1,365,through;Your leave will be unpaid.,1,0,After;" into sections divided by the commas into a 2d array. But it is not working. It says all of the values for the array are undefined. Here is where I call the function inside the ajax... (It works in the jsfiddle http://jsfiddle.net/ChaZz/3/)

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;
    }
  }

And here is the function 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;
}
0

2 Answers 2

2

http://jsfiddle.net/ChaZz/5/

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
Sign up to request clarification or add additional context in comments.

2 Comments

what does the console.log do?
The developer console that is in every modern browser.
0

There's no need for the loop to copy from mySplitArray2 to myArray, just assign the array returned by split directly to that element of the new array. And array.push can be used to build up an array incrementally.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.