我有三种类型的字符串。
This is a test.
I am testing.
This is a simple string.
我想获取不包含test
或testing
的字符串。这是第三个字符串。
我有一个值为test
和testing
的数组。
唯一的解决方案,我必须遍历数组并一一搜索字符串中的数组值。
$.each(myarray , function(index, val) {
if (string.indexOf(val) === -1) {
}
});
没有使用循环是否有更好的解决方案?
您可以使用some()
和includes()
功能进行操作。以下是有关some()和includes()的信息。
[includes()方法区分大小写
确切地说,some
和includes
函数在后台(引擎盖下)循环运行。但是,您不需要编写自己的循环。
$(document).ready(function() {
var strings = ['This is a test.', 'I am testing.', 'This is a simple string.'];
var excludes = ['test', 'testing'];
testFunction(strings, excludes);
function testFunction(strings, excludes) {
$.each(strings, function(index, string) {
if (!excludes.some(v => string.includes(v))) {
// here are just the strings which not includes substrings of "excludes"
$('#output').append(string);
}
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="output"></pre>