如何在javascript中迭代字符串数组和连接元素?

时间:2016-06-27 21:11:07

标签: javascript arrays string iteration

getPath(array,0)将返回" A"
 getPath(array,1)将返回" AB"
 getPath(array,2)将返回" ABC"

function getPath(arr, idx){  
  // todo ...     
}  
var array = ["A","B","C"];  

2 个答案:

答案 0 :(得分:2)

function getPath(arr, idx){  
  return (arr.slice(0, idx+1).join(""));  
}  

是的,你是对的,减少

答案 1 :(得分:0)

简单旧的循环风格:

 function getPath(arr, idx){
   var output="";  
    for(i=0;i<idx;i++){
    output= output + array[i]
    }
  return output;
}  
var array = ["A","B","C"];