从这些随机的字符串和数组中:
var str = "She folded her handkerchief neatly.";
var arr = ['foo', 'folded', 'bar', 'neatly'];
如何获取精简数组,该数组仅将值保留在字符串中?
var res = ['folded', 'neatly'];
答案 0 :(得分:2)
使用Array.filter()和String.match()
可以轻松完成此任务
var str = "She folded her handkerchief neatly.";
var arr = ['foo', 'folded', 'bar', 'neatly'];
let res = arr.filter(s => str.match(s));
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 1 :(得分:1)
您可以使用Array.filter
和String.includes
var str = "She folded her handkerchief neatly.";
var arr = ['foo', 'folded', 'bar', 'neatly'];
filteredArr = arr.filter(item => str.includes(item))
console.log(filteredArr);
答案 2 :(得分:0)
使用新的JS功能。您可以使用 ES6 public class RadioFragment extends Fragment {
Button b_play;
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
String stream = "http://streaming.radiodifusao.org:8110/stream?type=.mp3";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_radio, container, false);
b_play = (Button) view.findViewById(R.id.b_play);
b_play.setEnabled(false);
b_play.setText("LOADING");
b_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (started) {
started = false;
mediaPlayer.pause();
b_play.setText("PLAY");
} else {
started = true;
mediaPlayer.start();
b_play.setText("PAUSE");
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
return view;
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
b_play.setEnabled(true);
b_play.setText("PLAY");
}
}
@Override
public void onPause() {
super.onPause();
if (started) {
mediaPlayer.pause();
}
}
@Override
public void onResume() {
super.onResume();
if (started) {
mediaPlayer.start();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (prepared) {
mediaPlayer.release();
}
}
}
功能。
在 performance
includes()