js 权威指南 5th edition 学习笔记

string

1  string.length;

2  get the last character of  a string
   last_char = s.charAt(s.length-1);

3  to extract the second,third,fourth characters from a string a:
sub = s.substring(1,4);

4  to find the position of the first letter 'a' in a string
i = string.indexOf('a');


var n = 17;
binary_string = n.toString(2);    //evaluates to '10001'

octal_string = '0' + n.toString(8); //'021'
hex_string = "0x" + n.toString(16);// '0x11'

var n = 123456.789;
n.toFixed(0);  //'123457'
n.toFixed(2);  //'123456.79'
n.toExponential(1); //'1.2e+5'
n.toExponential(3); // '1.235e+5'
n.toPrecision(4);  // '1235e+5'
n.toPrecision(7);  // '123456.8'


converting string to numbers
1  var product = "21" * "2";   //product is the number 42
2   var number = string_value - 0;  //adding zero to a string value results in string concatenation rather than type conversion
3   more explicit way,call the Number() constructor as a function:
   var number = Number(string value);
Note: string-to-number conversion is overly strict. it works only with base-10 numbers, and although it allows leading and trailing spaces, it does not allow any nonspace characters to appear in hte string following the number.

  to allow more flexible conversions, you can use parseInt()(only integers) and parseFloat()(both integers and floating-point numbers). if a string begins with '0x' or '0X',parseInt() interprets it as a hexadecimal number.

   parseInt() can even take a second argumen specifying the radix (base) of the number to be parsed. Legal values are between 2 and 36. For example:
  parseInt("11",2);          // return 3
  parseInt("ff",16);        //return 255
  parseInt("77",10);       // return 77

  if parseInt() or parseFloat() cann't convert the specified string to a number, it returns NaN;

你可能感兴趣的:(学习笔记)