0

When I am using console.log to print the array length , it returns 0 . But in the console , if I write txt.length it returns the actual length (i.e 60 in my case) . For this reason I can't iterate through the txt array.

var txt;

function preload() {
  txt = loadStrings("DataProcess/outData.txt");
  console.log(txt);
  console.log(txt.length);
}
5
  • 2
    Can we see what happens in loadStrings function? As you're passing a path to a file to that function, it badly seems, that there's some asyncronous action taken in the function. Commented Apr 28, 2020 at 16:21
  • What is loadStrings() here? Commented Apr 28, 2020 at 16:22
  • it is the p5.js loadStrings function . p5js.org/reference/#/p5/loadStrings Commented Apr 28, 2020 at 16:23
  • @Zarif Visit this link p5 load string for string array you need use callback. callback: This is a function which is called after the function is successfully executed. The first argument for this function is the strings array. Commented Apr 28, 2020 at 16:24
  • 1
    Yep, "This method is asynchronous, meaning it may not finish before the next line in your sketch is executed". Commented Apr 28, 2020 at 16:25

1 Answer 1

1

You need to get the length in the callback. from the docs the function accepts 3 arguments

loadStrings(filename, [callback], [errorCallback])

meaning you should do something like this:

var txt;

function preload() {
  loadStrings("DataProcess/outData.txt", (res) => {
    txt = res
    console.log(txt.length);
  })

}
Sign up to request clarification or add additional context in comments.

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.