【问题标题】:conversiton to number doesn't work转换为数字不起作用
【发布时间】:2015-11-03 10:13:47
【问题描述】:

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

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

或者全部是字符串或者全部是数字。

感谢您的帮助。

【问题讨论】:

  • 不能正常工作是什么意思?

标签: javascript numbers parseint


【解决方案1】:
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

【讨论】:

  • 谢谢,我不知道 javascript 像数字一样解释或理解 NaN。
  • “不是数字”是一个数字似乎是矛盾的! javascript 的众多可爱品质之一,有时会让您印象深刻!
猜你喜欢
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 2015-05-09
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多