Javascript (325)
ฉันคิดว่านี่เป็นlogฟังก์ชั่นที่คุณกำลังมองหา:
function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()}
การใช้
<script>
function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()}
function doSomething() {
var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b);
}
doSomething();
var message = "...or just do it out here";
log(message + "!");
</script>
เอาท์พุต
log(a) = 123
log(b) = Hello, I am TrungDQ!
log(message + "!") = ...or just do it out here!
รหัสยาว
<script>
function log(msg) {
// Get the line number and offset of the line where is function is called
var lineInfo = (new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];
var lineNum = lineInfo.split(':')[1];
var charOffset = parseInt(lineInfo.split(':')[2]);
// Get the file source
request = new XMLHttpRequest();
request.open('GET', window.location.href, true);
request.onload = function() {
// Get file source code
var response = request.responseText;
// Get the `log` line
var line = response.split('\n')[lineNum - 1];
// Get the `log` statement
var logStatement = line.substr(charOffset - 1).split(';')[0];
// Print it
console.log(logStatement + ' = ' + msg);
};
request.send();
}
function doSomething() {
var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b);
}
doSomething();
</script>
ใช้ได้เฉพาะเมื่อวางสคริปต์ภายใน<script>แท็กซึ่งใส่ไว้ใน.htmlเอกสารเพราะจะส่งคำขอไปlocation.hrefยังรับซอร์สโค้ด JSfiddle, คอนโซลเครื่องมือ F12 Dev, ถูกฝัง.jsไฟล์ที่ไม่ทำงานฉันกำลังพยายามทำให้มันใช้ได้ทุกที่ ...
อย่างไรก็ตามคำถามนี้น่าสนใจ