如何避開 JavaScript 中意外的字串拼接?


在連線字串、多重字串和數字時,請使用反引號來避免意外的字串連線。

我們有以下選項:

const concatValue = 'John,David,Mike';
var friendNames= `${concatValue}`;

上面的值與字串和數字連線:

var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ;

以下為連線的完整 JavaScript 程式碼:

示例

const concatValue = 'John,David,Mike';
var friendNames= `${concatValue}`;
var studentNameWithFriends=` ${concatValue}| 'Carol' | 24 ` ;
console.log(friendNames);
console.log(studentNameWithFriends);

要執行以上程式,你需要使用以下命令:

node fileName.js.

這裡,我的檔名為 demo37.js

輸出

這將產生以下輸出:

PS C:\Users\Amit\JavaScript-code> node demo37.js
John,David,Mike
John,David,Mike| 'Carol' | 24

更新於: 01-Sep-2020

2K+ 瀏覽

開啟您的事業

透過完成課程取得認證

馬上開始
廣告
© . All rights reserved.