Why does it display undefined ?
function rush (filename){ (function(){ var res = filename.split("."); var b = res[res.lenght - 1]; return b; })(); } alert(rush("work.tt")); Thanks in advance!
Why does it display undefined ?
function rush (filename){ (function(){ var res = filename.split("."); var b = res[res.lenght - 1]; return b; })(); } alert(rush("work.tt")); Thanks in advance!
Why does it display undefined?
Because the rush function returns nothing.
If you remove all unnecessary function, you can write this:
function rush (filename){ (function(){...})(); } This clearly shows the absence of return . Therefore, the result of this function is always undefined .
Head- on solution - add return
function rush(filename) { return (function() { var res = filename.split("."); var b = res[res.lenght - 1]; return b; })(); } console.log(rush("work.tt")); When adding, you will notice that it still does not work. Since there is a typo
lenght -> length function rush(filename) { return (function() { var res = filename.split("."); var b = res[res.length - 1]; return b; })(); } console.log(rush("work.tt")); Now you can see that the self-calling function is not needed
function rush(filename) { var res = filename.split("."); var b = res[res.length - 1]; return b; } console.log(rush("work.tt")); Also, to get the last element of the array, you can use the pop function
function rush(filename) { return filename.split(".").pop(); } console.log(rush("work.tt")); function rush (filename){ var res = filename.split("."); return res[res.length - 1]; } alert(rush("work.tt")); Source: https://ru.stackoverflow.com/questions/559403/
All Articles