给出示例数组
public class MainActivity extends AppCompatActivity {
ImageView imgValue ;
Button btnDownload ;
EditText edtUrl ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgValue = findViewById(R.id.imgValue);
btnDownload = findViewById(R.id.btnDownload);
edtUrl = findViewById(R.id.edtUrl);
btnDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GetImage imageDownloader = new GetImage();
imageDownloader.execute("https://upload.wikimedia.org/wikipedia/commons/d/d7/Android_robot.svg");
}
});
}
private class GetImage extends AsyncTask<String,Void,Bitmap>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap downloadedImage = null ;
String theUrl = strings[0];
try {
URL url = new URL(theUrl);
InputStream stream = url.openStream() ;
downloadedImage = BitmapFactory.decodeStream(stream);
}
catch (Exception ex){
ex.printStackTrace();
}
return downloadedImage ;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imgValue.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, "ddd", Toast.LENGTH_SHORT).show();
}
}
}
在(普通)Js中,是否有可能有效地获得与两种给定颜色匹配的array =
[
["name1", ["blue", "yellow", "pink"], "id"],
["name2", ["green", "orange"], "id"],
["nameN", ["purple", "black", "white", "red"], "id"],
];
和name
(比如id
和red
)?
答案 0 :(得分:1)
您可以使用Array#find
方法根据条件获取特定元素,并可以使用Array#includes
方法检查数组是否包含特定值。
let array = [
["name1", ["blue", "yellow", "pink"], "id"],
["name2", ["green", "orange"], "id"],
["nameN", ["purple", "black", "white", "red"], "id"],
];
let color = 'orange';
let [name, colors, id] = array.find(a => a[1].includes(color));
console.log(name, id)
答案 1 :(得分:0)
您还可以使用 reduce :
const arr = [
['name1', ['blue', 'yellow', 'pink'], 'id'],
['name2', ['green', 'orange'], 'id'],
['nameN', ['purple', 'black', 'white', 'red'], 'id'],
];
const getNameAndIdByColor = (color) =>
arr.reduce(
(acc, [name, colors, id]) => (colors.includes(color) ? { ...acc, [color]: { name, id } } : acc),
{},
);
console.log('getNameAndIdByColor:', getNameAndIdByColor('red'));