【问题标题】:Is there a way to build a string out of an array in a specific order?有没有办法以特定顺序从数组中构建字符串?
【发布时间】:2017-01-23 20:19:41
【问题描述】:

我很好奇是否有办法以特定顺序从数组中构建字符串。到目前为止我的代码:

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];
  • 运行这段代码后我得到了undefinedcontentundefined
  • 你没有传入变量,你正在读取字符串......

标签: javascript arrays string loops


【解决方案1】:

只是一些小错误

  • 您需要将变量pcontent 传递给strConstruct 而不是字符串"pcontent"

  • 还有aname[newStrs[i]] 而不是aname[i]

  • cs初始化为空字符串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);

【讨论】:

    【解决方案2】:

    一种方法是

    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);

    【讨论】:

      【解决方案3】:

      您可以使用rest operator 作为参数的替换。

      稍后您可以映射字符串的字符,这里使用它而不是带有字母的数组。

      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);

      【讨论】:

      • 我喜欢这个解决方案的灵活性,但是当我尝试运行它时,我得到“Uncaught SyntaxError: unexpected token 。”
      • 这只是时间问题。很快就可以与 es6 一起使用。
      猜你喜欢
      • 2023-04-07
      • 2018-03-07
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      相关资源
      最近更新 更多