我需要从对象数组中的每个对象字段中删除“ hello”子字符串。
而且我有一个错误“无法读取null的属性'indexOf'”。发生这种情况是因为我尝试循环更改对象字段。但是该怎么办? :)
我使用AngularJS。



var array = [
    {text: 'hello user1'},
    {text: 'hello user2'},
    {text: 'user3'},
    {text: 'hello user4'},
];
for (i = 0; i < array.length; i++) {
    if (array[i].text.indexOf('hello') + 1) {
        array[i].text = array[i].text.replace('hello','');
    }
}

// For demo
document.write(JSON.stringify(array));

最佳答案

您的条件条件不正确。


  indexOf()方法返回第一次出现指定值的调用String对象内的索引,从fromIndex开始搜索。如果找不到该值,则返回-1


将您的条件更改为

if(array[i].text.indexOf('hello') > -1){
    //Rest of your code
}

07-24 18:46
查看更多