本文介绍了转换为数字不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释为什么这段代码不能正常工作:

Can anyone explain to me why this code doesn't works correctly:

var num = '10';

Number(num);
console.log(typeof(num));//string

parseInt(num);
console.log(typeof(num));//string

parseFloat(num, 10);
console.log(typeof(num));//string

console.log('-------------');

var num = '10';
var string = 'aklñjg';


num = Number(num);
string = Number(string);
console.log(typeof(num));//number
console.log(typeof(string));//number


num = parseInt(num);
string = parseInt(string);
console.log(typeof(num));//number
console.log(typeof(string));//number

console.log('++++++++++++++++');


    var num = '10';
var string = 'aklñjg';


num = Number(num);
string = Number(string);
console.log(typeof(num));//number
console.log(typeof(string));//number


num = parseInt(num, 10);
string = parseInt(string, 10);
console.log(typeof(num));//number
console.log(typeof(string));//number

或者 all 是一个字符串或者 all 是一个数字.

Or all is a string or all is a Number.

感谢您的帮助.

推荐答案

var num = '10'; // num is a string

Number(num); // you've done nothing with the RESULT, num is unchanged
console.log(typeof(num));//string - because you haven't changed num

parseInt(num); // you've done nothing with the RESULT, num is unchanged
console.log(typeof(num));//string - because you haven't changed num

parseFloat(num, 10); // you've done nothing with the RESULT, num is unchanged
console.log(typeof(num));//string - because you haven't changed num

var num = '10'; // num is a string
var string = 'aklñjg';  string is a string


num = Number(num); // num is a Number
string = Number(string);// string is a Number (NaN (not a number) is a number!)
console.log(typeof(num));//number
console.log(typeof(string));//number


num = parseInt(num); // num is a number
string = parseInt(string); // string is a number (NaN still a number)
console.log(typeof(num));//number
console.log(typeof(string));//number

这篇关于转换为数字不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:53