简体   繁体   中英

Javascript: concatenate function with the string

Following the question here:

JavaScript getting filename without extension located in different folder

I would like to concatenate this function with my string.

When I apply this code

"use strict";
window.addEventListener('load', onLoad, false);

function onLoad(evt) {
  let scripts = document.querySelectorAll('script');
  scripts.forEach(scr => {
    if (scr.src != '') {
      let slashPos = scr.src.lastIndexOf('/');
      let filename = scr.src.slice(slashPos + 1);
      filename = filename.replace('.js', '');
      //console.log(filename);
      return filename
    }
  });
}

var string = 'Date = ' + onLoad;

console.log(string)My console shows the full function instead of a certain date.

在此处输入图像描述

what should I do to have the date populated properly?

You need to execute the function. Like that:

const string = `Date = ${onLoad()}`;

You are not calling the function onLoad because there are no parenthesis, you are passing a reference to it which is your entire function.

var string = 'Date = ' + onLoad();

You are not running your function. You are doing something akin:

 function return_string() { return 'a string'; } var string = 'Date = ' + return_string; console.log( string );

That returns the function, not the result. So just execute the function as normal

 function return_string() { return 'a string'; } var string = 'Date = ' + return_string(); console.log( string );

This is happening because in javascript if you just call the function without braces it returns the function definition instead of actually invoking the function. So, calling onload like this would return its' function definition. You should call onload() to get the actual return value of the function. But then I saw there's no return from that function as well. So what are you expecting from this function to be returned? If you want to get Date inside JavaScript you should call the Date constructor like this new Date() to get the current Date. For more information on the Date constructor visit mdn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM