Skip to content

Instantly share code, notes, and snippets.

@s3rgeym
Last active December 29, 2016 22:39
Show Gist options
  • Save s3rgeym/4f4030a73185311d91170da4b42bd27b to your computer and use it in GitHub Desktop.
Save s3rgeym/4f4030a73185311d91170da4b42bd27b to your computer and use it in GitHub Desktop.
Нестрогое сравнение в JavaScript
/*
s='true,false,null,undefined,0,42,3.14159265359,NaN,Infinity,-Infinity'
a=s.split(',')
for x in a:
b.extend([x, ' \t\n' + x])
if x.upper() != x:
b.append(x.upper())
if x.lower() != x:
b.append(x.lower())
for x in b:
print(' {!r}, '.format(x))
*/
var data=[
// Boolean
true,
false,
new Boolean(true),
// Null
null,
// Undefined
undefined,
// Number
0,
42,
3.14159265359,
NaN,
Infinity,
-Infinity,
new Number(42),
// Object
{}, // empty plain object
{x:42}, // non-empty
// Array
[],
[42],
// Function
function(){},
// String
'foo',
new String('foo'),
// Дальше пошли обычные типы в строковом представлении (+с пробельными
// символами и в разных регистрах)
'true',
' \t\ntrue',
'TRUE',
'false',
' \t\nfalse',
'FALSE',
'null',
' \t\nnull',
'NULL',
'undefined',
' \t\nundefined',
'UNDEFINED',
'0',
' \t\n0',
'42',
' \t\n42',
'3.14159265359',
' \t\n3.14159265359',
'NaN',
' \t\nNaN',
'NAN',
'nan',
'Infinity',
' \t\nInfinity',
'INFINITY',
'infinity',
'-Infinity',
' \t\n-Infinity',
'-INFINITY',
'-infinity',
];
function repr(x){
if (typeof x === 'string'){
return "'" + x.replace(/\t/g, '\\t')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/'/g, "\\'") + "'";
} else {
return x;
}
}
for (let a of data){
// console.group('Test', a, typeof a);
console.groupCollapsed('Test', repr(a), typeof a);
for (let b of data){
if (b!==a){
console.log(typeof b,repr(b),'==',repr(a),b==a)
}
}
console.groupEnd();
}
@s3rgeym
Copy link
Author

s3rgeym commented Dec 29, 2016

Интересные вещи получаются:
[42]=='\t42' // true
'\t42'==new Number(42)// true
new Number('\t42')==42//true
42==['\42']//true
q=['\t42'];
console.log(++q);//43
q=['\t42',0];
console.log(++q);//NaN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment