我在js中没有太多练习但是我需要在我的项目中使用它。我将不胜感激任何帮助。
我需要访问Chrome控制台中显示的对象中的值,如附图所示。我想读出值距离和持续时间。如果我尝试以简单的数组distanceDuration [index]来访问它,我会得到“未定义的”#39;结果。我如何访问这些值?
obj.prop
答案 0 :(得分:0)
我不完全理解你的问题。使用索引@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try{
result = task.execute("thelinkIuse").get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
while (true) {
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
return "Failed";
}
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray arr = new JSONArray(result);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
symbols.add(jsonPart.getString("symbol"));
bids.add(jsonPart.getString("bid"));
asks.add(jsonPart.getString("ask"));
}
Log.i("Symbols", String.valueOf(symbols));
Log.i("Bids", String.valueOf(bids));
Log.i("Asks", String.valueOf(asks));
} catch (JSONException e) {
e.printStackTrace();
Log.i("failed", "failed");
}
}
}
访问数组中的第一个元素(距离),使用0
访问第二个元素(持续时间):
1
使用解构:
var distanceDuration = ['273 km', '2 hours 55 mins'];
var distance = distanceDuration[0];
var duration = distanceDuration[1];
但是,使用常规对象而不是数组似乎是更好的选择:
var distanceDuration = ['273 km', '2 hours 55 mins'];
var [distance, duration] = distanceDuration;