亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用數組的另一個值替換javascript中數組的值?

如何用數組的另一個值替換javascript中數組的值?

叮當貓咪 2023-05-11 10:12:17
我正在嘗試用另一個數組替換字符串中存在的數組中的值。在 Javascript 中執行此操作的最佳方法是什么?這是我的代碼:var string = "I've to but the Item1 along with Item2 and Item3. From the Item4."var array1 = ['Item1', 'Item2', 'Item3', 'Item4']var array2 = ['Product1', 'Product2', 'Product3', 'Product4']輸出應該是這樣的var replaced = "I've to but the Product1 along with Product2 and Product3. From the Product4."兩個數組中的每個值都完全不同。
查看完整描述

3 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

您可以使用String.prototype.replaceAll替換字符串

const input = "I've to but the Item1 along with Item2 and Item3. From the Item4.";

const original = ['Item1', 'Item2', 'Item3', 'Item4'];

const target = ['Product1', 'Product2', 'Product3', 'Product4'];


let result = input;

original.forEach((item, index) => {

? result = result.replaceAll(item, target[index]);

});


console.log(result);



查看完整回答
反對 回復 2023-05-11
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

我希望我有所幫助。


var array1 = ['Item1', 'Item2', 'Item3', 'Item4'];

var array2 = ['Product1', 'Product2', 'Product3', 'Product4'];

var string = "I've to but the Item1 along with Item2 and Item3. From the Item4.";


for (var i = 0; i < array1.length; i++) {

    var string = string.replace(array1[i], array2[i]);

}


console.log(string);


查看完整回答
反對 回復 2023-05-11
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

您可以使用模板文字,例如


var array1 = [Item1, Item2, Item3, Item4];

var array2 = [Product1, Product2, Product3, Product4]

var string = `I've to but the ${array1[0]} along with ${array1[1]} and ${array1[2]}. From the 

${array1[3]}.`

var replaced = `I've to but the ${array2[0]} along with ${array2[1]} and ${array2[2]}. 

From the ${array2[3]}.`


查看完整回答
反對 回復 2023-05-11
  • 3 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號