有没有一种方法可以按特定顺序从数组中构建一个字符串?

3

我想知道是否有一种方法可以按特定顺序从数组中构建字符串。 我目前的代码:

var pcontent = [ "h", "H", "o", " " ];
var constpass = strConstruct( "pcontent", 1, 2, 3, 0, 2, 3, 0, 2);

function strConstruct ( aname ) {

    var newStrs = arguments;
    var cs;

        for ( var i = 1; i < newStrs.length; i++ ) {
            cs = cs + aname[i];
        }
        return cs;
}

console.log( constpass );

运行时我得到了“contentundefinedcontent”的内容。
如果不可能,那就好好知道一下,谢谢。

cs = cs + aname[i]; => cs = cs + window[aname][i]; - Pranav C Balan
运行这段代码后,我得到了 undefinedcontentundefined - Wiktor Stribiżew
1
你没有传递变量,而是读取了字符串... - epascarello
3个回答

3

只有一些小错误

  • You need to pass the variable pcontent to strConstruct not the string "pcontent"

  • And aname[newStrs[i]] instead of aname[i]

  • Initializing cs to an empty string var cs = ""

    var pcontent = ["h", "H", "o", " "];
    var constpass = strConstruct(pcontent, 1, 2, 3, 0, 2, 3, 0, 2);
    
    function strConstruct(aname) {
      var newStrs = arguments;
      var cs = "";
      for (var i = 1; i < newStrs.length; i++) {
        cs = cs + aname[newStrs[i]];
      }
      return cs;
    }
    console.log(constpass);


1
你可以使用剩余参数运算符代替参数。
之后你可以映射字符串的字符,这里使用字符串代替字母数组。

function strConstruct(string, ...indices) {
    return indices.map(i => string[i]).join('');
}
  
var constpass = strConstruct("hHo ", 1, 2, 3, 0, 2, 3, 0, 2);

console.log(constpass);


我喜欢这个解决方案的灵活性,但是当我尝试运行它时,会出现“未捕获的SyntaxError:意外的标记。” - Tahj
这只是一个时间问题。很快就能使用ES6编译。 - Nina Scholz

0

做这件事的一种方法是

var pcontent = ["h", "H", "o", " "],
   constpass = (p, ...a) => a.reduce((s,k) => s+=p[k],""),
      result = constpass(pcontent, 1, 2, 3, 0, 2, 3, 0, 2);
console.log(result);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接