Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
黒魔術(JavaScript)まとめ ref: http://qiita.com/suetake/items/425684ac278c7cf8c30c
var foods = ['apple', 'banana', 'orange'];
if (~foods.indexOf('apple')) {
// appleが含まれていた時の処理
}
if (foods.indexOf('apple') !== -1) {
// appleが含まれていた時の処理
}
// 又は
if (foods.indexOf('apple') > -1) {
// appleが含まれていた時の処理
}
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(document.querySelectorAll('div')); // "[object NodeList]"
[].slice.call(arrayLikeObject).forEach(function(item) {
// 処理
});
new function() {
var a = eval('this'); // 直接eval
var b = (0, eval)('this'); // 間接eval
console.log(a, b); // Object {}, Window {...}
}
new function() {
var a = Function('return this')();
console.log(a); // Window {...}
}
++[[]][+[]]
+
[+[]]
++[[]][0]
+
[0]
var a = [];
++a; // 1
++1; // Uncaught ReferenceError: Invalid left-hand side expression in prefix operation
console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0); // -1
console.log(~1); // -2
console.log(~2); // -3
_=$=+[]
,
++_+''+$
1 + '' + 0
[NaN].indexOf(NaN); // -1
[NaN].includes(NaN); // true
// pt1
void function() {
return 'ok';
}();
// pt2
function() {
return 'ok';
}();
// pt3
[function() {
return 'ok';
}()]
// pt4
var hoge = function() {
return 'ok';
}();
// pt2
function() {
return 'ok';
};
(); // ← SyntaxError
// NG (SyntaxError)
function() {
return 'ok';
}();
// OK
(function() {
return 'ok';
})();
Array.prototype.slice.call(document.querySelectorAll('div')).forEach(function(div) {
console.log(div);
});
[1, 2, 3, 4, 5].forEach(function(item) {
// 処理
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment