var sentence = 'The quick brown fox jumped over the lazy dog.';
var word = ['fox'];
console.log('The word "' + word + (sentence.includes(word)? '" is' : '" is not') + ' in the sentence');
// expected output: "The word "fox" is in the sentence"
这是Javascript文档中的String.includes()
,但我想做的是这样的:
var sentence = 'The quick brown fox jumped over the lazy dog.';
var word = ['fox', 'dog'];
console.log('The word "' + word + (sentence.includes(word)? '" is' : '" is not') + ' in the sentence');
我想测试该句子的字符串数组,如果该数组中的字符串之一在句子中,则返回true
。但是如您在摘要中所见,它不起作用。
答案 0 :(得分:2)
我假设它为变量word
中的每个项目打印
就像
"The word "fox" is in the sentence"
"The word "dog" is not in the sentence"
你可以
var sentence = 'The quick brown fox jumped over the lazy dog.';
var word = ["fox", "dog"]
function test(word) {
console.log('The word "' + word + (sentence.includes(word) ? '" is' : '" is not') + ' in the sentence');
}
word.map((item) => {
return test(item)
})
答案 1 :(得分:1)
请尝试使用此选项,如果var word
中的一个与句子不匹配,则返回false,否则如果包含所有内容,则返回true。
var sentence = 'The quick brown fox jumped over the lazy dog.'
var word = ["fox", "the", "lol"]
var initialReturn = true
check = (word) => {
!sentence.includes(word) ? initialReturn = false : null
}
word.map(item => {
return check(item)
})
console.log("initialReturn", initialReturn)
答案 2 :(得分:0)
var sentence = 'The quick brown fox jumped over the lazy dog.';
var word = ['fox', 'dog'];
console.log('The word "' + word + (sentence.split(' ').some(d => word.includes(d)) ? '" is' : '" is not') + ' in the sentence');
答案 3 :(得分:0)
检查这段代码。我学到了使用弦乐的一件重要事情。正则表达式可以帮助您(但是很麻烦)并在您使用框架时使用扩展(函数,帮助器)。但是,如果您使用本机js indexOf会有所帮助。 我更新了我的答案。
var sentence = 'The quick brown fox jumped over the lazy dog.';
var words = ['fox', 'dog'];
console.log('The words: "' + words + (sentence.split(/[ ,.]/).some(function(e) { return words.indexOf(e) >= 0 })? '" is' : '" is not') + ' in the sentence');