jQuery - 从数组转换字符串

时间:2014-04-30 09:37:10

标签: jquery string

我有一个这样的数组:

var en_af = {
    "Hello": "Hallo",
    "World": "Wereld"
};

这样的字符串:

var str = "Hello World";

我的预期输出:

  

Hallo Wereld

所以我想用值替换键。

5 个答案:

答案 0 :(得分:1)

试试这个解决方案,

var en_af = {
    "Hello": "Hallo",
    "World": "Wereld"
};

var str = "Hello World";  //provide here keys to lookup in en_af array

var keys_from_str=str.split(" "); //making an array of keys from given string.

var output_string="";
for(i=0;i<keys_from_str.length;i++){  
   output_string+=en_af[keys_from_str[i]]+" ";  //get value for respected key from en_af and concatenate with output_string
}
output_string=output_string.trim(); //removing last extra space
console.log(output_string);

演示jsFiddle

答案 1 :(得分:0)

尝试,拆分并获取原始数组的索引值:

var str = "Hello World";
var res = str.split(" ");

var output="";
for(var i =0; i < res.length-1;i++){
 output += en_af[res[i]];
}

答案 2 :(得分:0)

var str_output = "";

首先拆分键阵列

var keys_array = str.split(' ');

并迭代它

keys_array.each(function(index, value) {
   str_output = str_output + " " + en_af.value;
});

删除第一个和最后一个空格

$.trim(str);

答案 3 :(得分:0)

str = str.split(" ");
output = en_af.str[0] +" "+ en_af.str[1];

如果strg是&#34; Hello World&#34;

,你可以像Hallo Wereld一样得到输出

答案 4 :(得分:0)

        var str = "Hello World";
        $(str.split(' ')).each(function (i, v) {
            $('body').append(' ' + en_af[v]);
        });

演示:http://jsfiddle.net/B8x4C/