在.replace()函数在该变量上运行后,在Json对象中不起作用的变量作为键

Variable not working in Json object as key after .replace() function is run on that variable?

本文关键字:变量 对象 不起作用 Json replace 函数 运行      更新时间:2023-09-26

json将不接受在该变量(myimg)上使用.replace()后存储url的变量,如下所示:

$.get('http://api.soundcloud.com/resolve.json?url=https://soundcloud.com/'+user_name+'/tracks&client_id='+my_client_id, 
      function (result) {
        for (var i = 0; i < result.length; i++) {
            var myimg = result[i].artwork_url;
            var myimg = myimg.replace('-large', '-t500x500'); //problem line of code making the  variable not usable in json object below.
            trackdata[i] = {
                             title: result[i].title,
                             mp3: result[i].stream_url + '?client_id=' + my_client_id,
                             url: result[i].permalink_url,
                             poster: myimg, // not working if i use .replace() on myimg var above , works without it
                             sc: "true"
                           }
         }  
 for (i = 0; i < trackdata.length; i++) {
        playlist.push(trackdata[i]);
    } 
});

如果我去掉这一行:

var myimg = myimg.replace('-large', '-t500x500');

变量将工作,但我想在传递给json对象之前替换url中的字符串。这将允许我将url更新为这个问题中详细的更高质量的图像:Soundcloud默认500x500 artwork

Move

for (i = 0; i < trackdata.length; i++) {
  playlist.push(trackdata[i]);
}

在你的$.get中,这看起来就像它只是一个竞争条件(假设问题是"图像没有显示在网页上",而不是javascript错误本身)。

我真的不明白你说的"工作"answers"不工作"是什么意思,但是。replace在你的情况下应该没有任何作用。

应该将最后一个for循环移到$。获取或将其放入函数中,并在$中调用该函数。Get,因为它表示for循环(可能)会在$之前被调用。Get调用返回,回调函数被调用。这是你的问题吗?

$.get("...", function() {
  // you will reach here after you have a response
  // do stuff
  // run your for loop
}
// code here could get reached before you have a response from your get request

你也应该使用trackdata.push({…});还要确保你的arwork_url看起来像你认为它应该看起来的样子,也许将它添加到你的js对象中,并与poster属性一起查看它以获得更多信息。

由于我没有SoundCloud的ClientId,因此我无法在实践中对此进行测试,但理论上这样的东西可以实现我相信您正在尝试做的事情:

$.get('http://api.soundcloud.com/resolve.json?url=https://soundcloud.com/'+user_name+'/tracks&client_id='+my_client_id, 
    function (result) {
        var trackdata = [];
        result.forEach(function(the) {
            trackdata.push({
                title: the.title,
                mp3: the.stream_url + '?client_id=' + my_client_id,
                url: the.permalink_url,
                poster: the.artwork_url.replace('-large', '-t500x500'),
                sc: "true" // Hmm... why is this a string?
            });
        });
        // BTW, why the intermediate trackdata-array?
        trackData.forEach(function() {
            playlist.push(trackdata[i]);
        });
    });