试图返回一个对象数组但是在函数内部循环冻结

时间:2018-01-27 21:21:09

标签: arrays callback return

var uri = ['https://open.spotify.com/album/51vRvV83RdWGP9FpzGe4SQ','https://open.spotify.com/user/diplomaddecent/playlist/6AvLNaeJ7qeF1Ur1kNoiXT','https://open.spotify.com/user/spotify/playlist/37i9dQZF1DX4dyzvuaRJ0n']

function seperateUri(uri,callback){

    for (var i=0;i<uri.length;i++)
    {
       function callback(result){
                                 return {
                                        type: result[2],
                                        id: result[3]
                                        }
                                }

     var parse_uri = /[a-z]+:\/{0,2}(open.spotify.com)\/(\w+)\/(\w+)$/i ;
     result = parse_uri.exec (uri [i] ) ;
     return this [i] = callback(result) ;
     }
} 



seperateUri(uri);

2 个答案:

答案 0 :(得分:0)

var results = {} ;
function seperateUri(uri,callback){

    for (var i=0;i<uri.length;i++)
    {
       function callback(result){
                             return {
                                    type: result[2],
                                    id: result[3]
                                    }
                            }

     var parse_uri = /[a-z]+:\/{0,2}(open.spotify.com)\/(\w+)\/(\w+)$/i ;
     result = parse_uri.exec (uri [i] ) ;
     results[i] = callback(result) ;
     }
} 



seperateUri(uri); //populates the results object

results对象将保存小孩result个对象。你可以访问各个结果对象并随意使用它们,但是return关键字过早地破坏了你的循环。

答案 1 :(得分:0)

这是解决方案

var uri = ['https://open.spotify.com/album/51vRvV83RdWGP9FpzGe4SQ','https://open.spotify.com/album/3CsiXF2gHbhWGW38GKnZln','https://open.spotify.com/album/2zINKv6Jg7zVf6Od61itzs']

function seperateUri(uri,callback){

for (var i = 0; i < uri.length; i++) {


    var parse_uri = /[a-z]+:\/{0,2}(open.spotify.com)\/(\w+)\/(\w+)$/i;
    result = parse_uri.exec(uri[i]);
    this[i] = callback(result, i);

    function callback(result, i) {


        this[i] = {
            type: result[2],
            id: result[3]
        }

        return this[i]

    }


}
return this

}

的console.log(seperateUri(URI)[1] .ID)