📜  JavaScript Object.prototype.toLocaleString() 方法

📅  最后修改于: 2022-05-13 01:56:39.245000             🧑  作者: Mango

JavaScript Object.prototype.toLocaleString() 方法

Object.prototype.toLocaleString() 方法使用环境的语言环境返回此对象的本地特定字符串表示。数组、数字、日期、typedarray 和 BigInt 等派生对象可以覆盖此方法。

句法:

object.toLocaleString()

返回值:它返回此对象的字符串表示形式。

覆盖 toLocaleString() 的对象:

1. 数组到Array.prototype.toLocaleString() 返回此数组对象的字符串表示形式。

例子:

Javascript
// User inputs.
var name = [ "sahil", "zain", "deepanshu" ];
var number1 = 3.45;
var number2 = [ 23, 34, 54 ];
  
var arr = [ name, number1, number2 ];
    
// Applying array.toLocaleString function
var string = arr.toLocaleString();
    
// Printing string.
console.log(string);


Javascript
var Big = 45334n;
console.log(Big.toLocaleString());
  
Big =78753456789123456789n;
console.log(Big.toLocaleString('de-DE'));


Javascript
var d = new Date(Date.UTC(2020, 9, 26, 7, 0, 0));
var result = d.toLocaleString();
   console.log("Date and Time of apocalypse: "+ result);


Javascript
// Declaring an variable 
  var a = new Number(159900);
    
  // Creating an dictionary like object and
  // include currency and style
  var myObj = {
    style: "currency",
    currency: "EUR"
  }
    
  console.log(a.toLocaleString("en-GB", myObj));


Javascript
var geek = new Uint32Array([100, 897, 123, 132, 22]);
    
console.log(geek.toLocaleString()); 
    
console.log(geek.toLocaleString('en-US'));
    
console.log(geek.toLocaleString('hi', 
    { style: 'currency', currency: 'HIR' }));


输出:

"sahil, zain, deepanshu, 3.45, 23, 34, 54"

2. BigInt to BigInt.prototype.toLocaleString() 它返回这个 BigInt 对象的字符串表示。

例子:

Javascript

var Big = 45334n;
console.log(Big.toLocaleString());
  
Big =78753456789123456789n;
console.log(Big.toLocaleString('de-DE'));

输出:

"45, 334"
"78.753.456.789.123.456.789"

3. Date to Date.prototype.toLocaleString() 它返回这个日期对象的字符串表示。

例子:

Javascript

var d = new Date(Date.UTC(2020, 9, 26, 7, 0, 0));
var result = d.toLocaleString();
   console.log("Date and Time of apocalypse: "+ result);

输出:

Date and Time of apocalypse: 26/10/2020, 12:30:00

4. Number to Number.prototype.toLocaleString() 它返回这个数字的字符串表示。

例子:

Javascript

// Declaring an variable 
  var a = new Number(159900);
    
  // Creating an dictionary like object and
  // include currency and style
  var myObj = {
    style: "currency",
    currency: "EUR"
  }
    
  console.log(a.toLocaleString("en-GB", myObj));

输出:

€159,900.00

5. TypedArray to TypedArray.prototype.toLocaleString() 它返回一个字符串,代表typedArray的元素。

例子:

Javascript

var geek = new Uint32Array([100, 897, 123, 132, 22]);
    
console.log(geek.toLocaleString()); 
    
console.log(geek.toLocaleString('en-US'));
    
console.log(geek.toLocaleString('hi', 
    { style: 'currency', currency: 'HIR' }));

输出:

"100, 897, 123, 132, 22"
"100, 897, 123, 132, 22"
"HIR 100.00, HIR 897.00, HIR 123.00, HIR 132.00, HIR 22.00"

支持的浏览器:

  • 谷歌浏览器
  • IE浏览器
  • 火狐
  • 苹果浏览器
  • 歌剧