在.replace()函数在该变量上运行后,在Json对象中不起作用的变量作为键
Variable not working in Json object as key after .replace() function is run on that variable?
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]);
});
});
相关文章:
- 替换另一个变量对象中的变量值
- 如何从表单变量对象中获取特定的from属性
- 变量/对象是否按值传递,为什么我不能在 javascript 中使用变量更改对象的属性
- 执行上下文和变量对象在 JavaScript 中实际上是一回事吗?
- 如何将变量对象传递到多个javascript弹出窗体
- 如何将javascript变量/对象从一个页面传递到另一个页面
- 在具有递增的变量/对象中存储和控制传单 GeoJSON 图层
- 在回调中重用变量/对象
- 给一个有1个变量/对象的函数给定几个参数
- 使用单词'英语'因为变量/对象名称在javascript中不起作用
- 如何访问变量对象中的数据
- 使用onclick调用变量对象中的函数
- 使用Underscore JS部分和for循环的未定义变量对象
- 如何查看我的变量对象
- 变量对象属性名称作为javascript中的参数
- 从变量对象中移除DOM元素,以便将其发布到服务器
- 根据变量对象是否等于“true”输出内容
- 如何连接(变量+对象键名)以获得点表示法的对象值
- 为什么在ES5中将变量对象改为词法环境
- 动态引用变量(对象)