如果元素中包含特定字符,如何删除它?

时间:2016-12-24 07:06:42

标签: javascript arrays

如果元素包含特定值,我想从数组中删除元素。

var array = [hello@yahoo.com, www.hello.com, hello@gmail.com];

我想删除带@符号的al元素。当我提醒阵列时,我只需要www.hello.com。

4 个答案:

答案 0 :(得分:1)

public class Adapterrecharge extends RecyclerView.Adapter<Adapterrecharge.MyViewHolder> {

private List<GetRecharge> rechargeList;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    ImageView image;

    public MyViewHolder(View view) {
        super(view);
        image = (ImageView) view.findViewById(R.id.image);
        title = (TextView) view.findViewById(R.id.title);

    }
}


public Adapterrecharge(List<GetRecharge> rechargeList) {
    this.rechargeList = rechargeList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.rechargelist, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    GetRecharge recharge = rechargeList.get(position);
    holder.title.setText(recharge.getTitle());
    holder.image.setImageDrawable(recharge.getImage());

}

@Override
public int getItemCount() {
    return rechargeList.size();
}
}

答案 1 :(得分:0)

一种方法是使用Regular Expression和另一个数组,如下所示:

var array = ['hello@yahoo.com', 'www.hello.com', 'hello@gmail.com'];
var array2 = [];
for (var i = 0; i < array.length; i++) {
  if (!(/@/.test(array[i]))) {
    array2.push(array[i]);
  };
};
alert(array2);

答案 2 :(得分:0)

避免删除/更改循环内数组元素的索引。这是因为在执行public class Sample { //Create a static final object private static final Sample INSTANCE = new Sample(); //private constructor, so this class can't instantiated from outside private Sample() { } //Use the getInstance() static method which returns same instance always public static Sample getInstance() { return INSTANCE; } private String name = "Sample Enum"; private String version = "1"; public String getName() { return this.name; } public String getVersion() { return this.version; } } public class App { public App() { System.out.printf("%s - %s",Sample.getInstance().getName(), Sample.getInstance().getVersion()); } } 时正在重新索引数组,这意味着当删除索引时,您将跳过索引,

相反,您可以过滤掉元素并获得符合条件的新数组

.splice()

DEMO

答案 3 :(得分:0)

您还可以将输入数组和匹配的push元素循环到输出数组

var array = [
'hello@yahoo.com',
'www.hello.com',
'hello@gmail.com'];
var newArray = [];
array.forEach(x => { 
  if(x.indexOf('@') === -1) 
     newArray.push(x);
});
console.log(newArray)