更簡單的方式將 indexOf 當作 contains 使用
JavaScript 預設沒有 contain 的方法。如果要檢查字串或是陣列內是否有子字串的存在你可以這樣做:
var someText = 'javascript rules';
if (someText.indexOf('javascript') !== -1) {
}
// or
if (someText.indexOf('javascript') >= 0) {
}
但是,讓我看一下這些 Expressjs 程式碼片段。
for (var key in obj) {
// "reserved" exports
if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue;
exports.normalizeType = function(type){
return ~type.indexOf('/')
? acceptParams(type)
: { value: mime.lookup(type), params: {} };
};
// key 是無效的
if (!~apiKeys.indexOf(key)) return next(error(401, 'invalid api key'));
困難的地方是位元運算符 ~,「位元運算符在二進制執行它們的操作,但是它們回傳的是標準 JavaScript 數值」。
它將 -1
轉換成 0
,而 0
在 JavaScript 當作 false
:
var someText = 'text';
!!~someText.indexOf('tex'); // someText 包含 "tex" - true
!~someText.indexOf('tex'); // someText 不包含 "tex" - false
~someText.indexOf('asd'); // someText 不包含 "asd" - false
~someText.indexOf('ext'); // someText 包含 "ext" - true
String.prototype.includes()
ES6 提供了 includes() 方法,你可以使用它來判斷字串是否包含在其他字串:
'something'.includes('thing'); // true
在 ECMAScript 2016(ES7)中,在陣列甚至有可能可以使用這些方法:
!!~[1, 2, 3].indexOf(1); // true
[1, 2, 3].includes(1); // true
不幸的是,這只支援在 Chrome、Firefox、Safari 9 或是更高版本的 Edge;在 IE11 或更低版本則無法使用。 它最好在被控制的環境下使用。

MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW

MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW