3

我有这个数组:

suggestions = [ "the dog", 
                "the cat", 
                "the boat",
                "boat engine",
                "boat motor",
                "motor oil"
              ];

如何遍历数组并删除包含特定单词的所有条目?

例如,删除所有包含单词“the”的整数,因此数组变为:

[ "boat engine",
  "boat motor",
  "motor oil"
];
4

4 回答 4

3

创建一个新数组可能更容易:

var correct = [],
    len = suggestions.length,
    i = 0,
    val;

for (; i < len; ++i) {
    val = suggestions[i];
    if (val.indexOf('the') === -1) {
        correct.push(val);
    }
}
于 2013-05-23T05:57:08.770 回答
1

我会使用这个设置:

var suggestions = [
    "the dog",
    "the cat",
    "he went then",
    "boat engine",
    "another either thing",
    "some string the whatever"
];

function filterWord(arr, filter) {
    var i = arr.length, cur,
        re = new RegExp("\\b" + filter + "\\b");
    while (i--) {
        cur = arr[i];
        if (re.test(cur)) {
            arr.splice(i, 1);
        }
    }
}

filterWord(suggestions, "the");
console.log(suggestions);

演示:http: //jsfiddle.net/Kacju/

它向后循环,正确检查要查找的单词(通过使用\b标识符作为单词边界),并删除任何匹配项。

如果要生成包含匹配项的新数组,请正常循环,并且只push对新数组的任何不匹配项进行循环。你可以使用这个:

var suggestions = [
    "the dog",
    "the cat",
    "he went then",
    "boat engine",
    "another either thing",
    "some string the whatever"
];

function filterWord(arr, filter) {
    var i, j, cur, ret = [],
        re = new RegExp("\\b" + filter + "\\b");
    for (i = 0, j = arr.length; i < j; i++) {
        cur = arr[i];
        if (!re.test(cur)) {
            ret.push(cur);
        }
    }
    return ret;
}

var newSuggestions = filterWord(suggestions, "the");
console.log(newSuggestions);

演示:http: //jsfiddle.net/Kacju/1/

于 2013-05-23T06:06:45.860 回答
0

尝试使用正则表达式

var suggestions = [ "the dog", 
                "the cat", 
                "the boat",
                "boat engine",
                "boat motor",
                "motor oil"
              ];
var filtered = [],
    len = suggestions.length,
    val,
    checkCondition = /\bthe\b/;

for (var i =0; i < len; ++i) {
    val = suggestions[i];
    if (!checkCondition.test(val)) {
        filtered.push(val);
    }
}

检查小提琴

于 2013-05-23T06:05:22.353 回答
-2

使用 ECMAScript5 的强大功能:

suggestions.reduce (
  function (r, s) {!(/\bthe\b/.test (s)) && r.push (s); return r; }, []);
于 2013-05-23T06:02:34.683 回答