js转换成数字

/**
 * 转换成数字,有两种方法:
 * 1.Number(var)
 * 2.parseInt(var)与parseFloat(var)
 */
// 字符串转换成数字
// 纯字母
var foo = 'hello';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): NaN
// 字母数字混合
var foo = 'hello123';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): NaN
// 纯数字
var foo = '8848';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 8848
var foo = '3.14234';
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 3.14234
// boolean
var foo = true;
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 1
var foo = false;
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 0
// null
var foo = null;
console.log(`Number(foo): ${Number(foo)}`); // Number(foo): 0
// undefined
var foo = undefined;
console.log(`typeof foo: ${typeof foo}, Number(foo): ${Number(foo)}`); // typeof foo: undefined, Number(foo): NaN
// 字母数字混合
// 字母在前
var foo = 'hello123';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
// 字母在后
var foo = '123hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 123
// 穿插
var foo = '13word23hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 13
var foo = 'w13ord23hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
// 夹带浮点数
var foo = 'hello23.54';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN
var foo = '23.54hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 23
var foo = '0.999hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): 0
var foo = 'wor0.999hello';
console.log(`parseInt(foo): ${parseInt(foo)}`); // parseInt(foo): NaN

猜你喜欢

转载自www.cnblogs.com/goujian/p/11704554.html