简体   繁体   English

返回不适用于 JS,但 console.log 可以

[英]return not working on JS but console.log does

I was trying to set these to work for a simple if else, but return on 2nd argument in Else part doesnt return anything but if I use `console.log('Its not a string');} it works.我试图将这些设置为一个简单的 if else 工作,但返回 Else 部分的第二个参数不返回任何内容,但如果我使用 `console.log('Its not a string');} 它可以工作。 Can someone enlighten me about it.有人可以启发我。

 let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); //prints String is a string// i = 100, typeof i; if (i == 'string') { return ('Its a string.'); } else { return ('Its not a string.'); }

return (which is a statement, not a function, so the parenthesis are pointless here) passes data back to the calling function . return (这是一个语句,而不是 function,所以括号在这里没有意义)将数据传递回调用 function

Your code isn't in a function.您的代码不在 function 中。 There is nowhere for it to be returned to.它无处可归。

For return to do anything you need to put it inside a function, call that function, and then do something with the return value.return做任何事情,你需要把它放在一个 function 中,调用它 function,然后对返回值做一些事情。

 function example() { let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); i = 100, typeof i; if (i == 'string') { return 'Its a string.'; } else { return 'Its not a string.'; } } let return_value = example(); document.body.appendChild( document.createTextNode(return_value) );

I guess you very new to programming.我猜你对编程很陌生。 You need to learn more about functions, datatype, program flow etc.您需要了解有关函数、数据类型、程序流程等的更多信息。

what you are doing can be done like this:你正在做的事情可以这样做:

 let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); //prints String is a string// i = 100; if (typeof i == 'string') { console.log('Its a string.'); } else { console.log('Its not a string.'); }

or you can do it like this:或者你可以这样做:

 let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); //prints String is a string// i = 100; console.log(isString(i)); function isString(i){ if (typeof i == 'string') { return('Its a string.'); } else { return('Its not a string.'); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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