2016-09-15 30 views
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」

如果是不可能的,這將是很好的瞭解,感謝

+0

'CS = CS + aname [I];'=>'CS = CS +窗口[aname] [I];' –

+0

我得到'運行此代碼後undefinedcontentundefined'。 –

+1

你沒有傳入變量,你正在讀取字符串.... – epascarello

回答

3

只是一些小的失誤

  • 您需要將變量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);

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

1

您可以使用rest operator作爲參數的替代。

稍後,您可以映射字符串的字符,這裏使用的是字符而不是數組。

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

 
console.log(constpass);

+0

我喜歡這個解決方案的靈活性,但是當我嘗試運行它時,我得到「Uncaught SyntaxError:unexpected token。」。 – Tahj

+0

這是時間問題。很快這將與es6一起工作。 –

相關問題