javascript - 如何用另一个数组值替换javascript中的数组值?
问题描述
我正在尝试用另一个数组替换字符串中存在的数组中的值。在 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."
两个数组中的每个值都彼此完全不同。
解决方案
我希望我对您有所帮助。
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);
推荐阅读
- machine-learning - XGBoost predict_proba 推理性能慢
- docker - Visual Studio 2019 错误 CTC1001:未启用卷共享
- reactjs - Django,Djoser 社交身份验证:在服务器端会话数据中找不到状态。状态码 400
- c - 我将如何创建一个函数来确定文件是否存在?
- python - 冻结的数值数组、数据类、numba
- python-3.x - 您是否使用此功能获得索引错误?
- sql-server - 使用 varbinary 参数更新存储过程中的语句
- python - 写很多列(超过20)
- c++ - 返回 x; 在 C++ 中没有返回整数值
- c - 安装 Gstreamer 插件,缺少 avi demuxer