簡體   English   中英

返回不適用於 JS,但 console.log 可以

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

我試圖將這些設置為一個簡單的 if else 工作,但返回 Else 部分的第二個參數不返回任何內容,但如果我使用 `console.log('Its not a string');} 它可以工作。 有人可以啟發我。

 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 (這是一個語句,而不是 function,所以括號在這里沒有意義)將數據傳遞回調用 function

您的代碼不在 function 中。 它無處可歸。

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) );

我猜你對編程很陌生。 您需要了解有關函數、數據類型、程序流程等的更多信息。

你正在做的事情可以這樣做:

 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.'); }

或者你可以這樣做:

 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