用多个数组值jquery替换字符串

时间:2017-04-27 05:23:15

标签: jquery performance

我有

 array1=["priya","reena","mathew"],
 array2=["teacher","developer","clerk"]
 my_str="hi{data} your profession is {data2}",

我需要将来自array1和{data2}的值的{data}替换为array2中的值。我的最终输出应该是:

 final_arr=["hi priya your profession is teacher","hi reena your profession is developer","hi mathew your profession is clerk"]

我可能会获得近10,000个输入,因此如何有效地使用jquery实现此目的。

4 个答案:

答案 0 :(得分:2)

使用javascript



var array1=["priya","reena","mathew"];
var array2=["teacher","developer","clerk"];

var final_arr=[];
var i;
for (i = 0; i < array1.length; i++) {
    final_arr.push("hi "+array1[i]+" your profession is "+ array2[i]);
}

for (i = 0; i < final_arr.length; i++) {
  document.write(final_arr[i]+ "<br>");
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用forEach循环在数组上循环。使字符串模式成为你想要的东西,并与循环值连接。 Ans基于假设您的array1和array2 lenth相等。

 
var array1 = ["priya", "reena", "mathew"];
var array2 = ["teacher", "developer", "clerk"];
var my_str = "hi{data} your profession is {data2}";
var fin_arr = [];
array1.forEach(function(index, item) {
  var res = 'hi ' + array1[item] + ' your profession is ' + array2[item];
  fin_arr.push(res);
});
console.log(fin_arr[0]);
console.log(fin_arr[1]);
console.log(fin_arr[2]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

var array1=["priya","reena","mathew"];
var array2=["teacher","developer","clerk"];

var result = [];
for(var i=0; i<array1.length; i++){
  result[i] = 'hi '+ array1[i]+' your profession is '+array2[i];
}

答案 3 :(得分:0)

function array_combine(a, b) {
  if(a.length != b.length) {
    return false;
  } else {
    new_array = new Array();
    for (i = 0; i < a.length; i++) {
      new_array[a[i]] = b[i];
    }
    return new_array;
  }
}

var combined_array = array_combine(array1, array2);

var output = [];
for(key in combined_array) {
  output.push("Hi "+key+" your profession is "+combined_array[key]);
}
console.log(output);