javascript - Return value after function execution is completed
Karen Carpenter
Karen Carpenter 2017-05-19 10:09:36
0
2
422

I would like to ask a question. I have a function that is relatively long and has a lot of logic. Then I define an empty array at the beginning of the function. The function of the function is to add elements to the array and then return the array. The problem I am encountering now is that when the function returns an array, it returns an array of length
such as a picture with a length of 0. So I would like to ask if there is any other way besides setTimeout({}) to make the function return the content after it is executed

Karen Carpenter
Karen Carpenter

走同样的路,发现不同的人生

reply all (2)
習慣沉默

To be honest, I didn’t understand the question you wanted to ask, and I didn’t see the code. After reading the conversation between you and above, I’m still confused. I can only speak based on my own guess.

1. First of all, what you said above is correct. The length is not 0. For the length of array, please look at the value of length. Yours is 1, so there is no problem

2. Secondly, the content printed in the console may not be complete. For example, when the relevant array is still in the operation process, whether adding or deleting elements in the array will not be directly reflected in the console, only the An update will only occur when you perform an operation, such as clicking on it or restarting the console.

3. As for how to return the array after the function has finished running, this is a very vague question. First of all, you need to check whether there are asynchronous operations in your function, such as onload events. If not, just return on the last line of the function. If so, you may need to find other ways to handle the content. To give a chestnut:

var imgArr = ["1.jpg","2.jpg","3jpg"]; //你想要在数组中的图片全部加载完然后转换成base64后再返回数据 var canvas = document.createElement("canvas"), copyArr = imgArr.concat(); var getB64Img = function(resultArr){ resultArr = resultArr || []; var img = document.createElement('img'), url = copyArr.shift(); if(!url) return resultArr; img.onload = function(){ //这里通过canvas转64码 resultArr.push(result); //保证了异步队列是排队实现 getB64Img(resultArr); }; img.src = url; }; var resultArray = getB64Img(); //过程大概就这样
    Ty80

    Friends, the length of this array is 1. Array[0] refers to the array element with index value 0, which is the {src: "..."} there. What do you mean when a function returns after execution? The setTimeout function is generally used to delay the execution of functions or expressions.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!