Question:
I am learning JavaScript. The task from the tutorial:
Write a function checkSpam (str) that returns true if str contains "html" or "css", otherwise false. The function must be case insensitive:
Answer from the tutorial:
function checkSpam(str) {
var lowerStr = str.toLowerCase();
return !!(~lowerStr.indexOf('html') || ~lowerStr.indexOf('css'));
}
alert( checkSpam('hTml now') );
alert( checkSpam('free cSs') );
alert( checkSpam("more java") );
Questions:
- I am confused by the presence at once !! and ~
How is the return line read? "If not found, then return …"
first sign ! = Not , and cast to a boolean type; further misunderstandings due to ~ and the second negation. - Here is my version, it seems clearer to me:
function checkSpam(str) {
var lowerStr = str.toLowerCase();
return (lowerStr.indexOf('html') != -1 || lowerStr.indexOf('css') != -1);
}
alert( checkSpam('hTml now') );
alert( checkSpam('free cSs') );
alert( checkSpam("more java") );
Is there a difference in these options and which type is more preferable?
Answer:
Sign !
denotes не
.
If you write return (~lowerStr.indexOf('html') || ~lowerStr.indexOf('css'))
it will just print the position of the words.
If you type return !(~lowerStr.indexOf('html') || ~lowerStr.indexOf('css'))
, but it outputs true/false
, while false
output if the word was found
And when you enter two !!
, then it will output true
, where false
and vice versa
The ~
sign returns the value -(число + 1)
.
Those. in your case, if the position is -1
, then it outputs 0
and at the same time false
is displayed in the condition, and if another number is any, then it is true