Skip to content

我也来推荐一个吧 Intl实例的运用 #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
eward957 opened this issue Dec 3, 2017 · 4 comments
Open

我也来推荐一个吧 Intl实例的运用 #21

eward957 opened this issue Dec 3, 2017 · 4 comments
Labels

Comments

@eward957
Copy link

eward957 commented Dec 3, 2017

  1. 字符串对比:

exp: 排序'我','爱', 以往我们会用localeCompare进行,但是也可以用

new Intl.Collator().compare('我','爱');

PS: 推荐在字符串超长时,或者长字符串数组时使用

  1. 数字格式化:
    exp: 将1000转化为1,000,这个特性大大有用啊 再也不用自己手写了
new Intl.NumberFormat().format(1000); // '1,000'

PS: 当然也可以使用:

既然楼下有提到,就都写出来吧:
console.log(99757..toLocaleString('en-US')); //99,757
//正则
const test = num => String(num).replace(/(^|\s)\d+/g, s => s.replace(/(?=(?!\b)(\d{3})+$)/g, ','))

  1. 时间格式化:
    exp: 将时间格式化为2017-12-3
new Intl.DateTimeFormat().format(new Date()); //'2017-12-3';

PS: 也可以使用

console.log(new Date().toLocaleDateString()); //兼容性好点

PS:当然每个都有更加高级的配置,可以自定制,这个太多了,记不住,用的时候再去查就好了,现在赖得去查,各位看官也可以自己去瞅瞅ecmascript文件;

@justjavac
Copy link
Owner

文档 Intl - MDN

兼容性:https://caniuse.com/#search=Intl

@islishude
Copy link

islishude commented Dec 4, 2017

数字格式化那个,更简单是 (123123).toLocaleString('en-US') 而且兼容 Node,不过这个和上面那个 i18 与正则的方式相比速度慢了20倍,我在生产环境是不用这个的。

@eward957
Copy link
Author

eward957 commented Dec 4, 2017

@islishude 哈哈 经你提醒 那我还是把其他的都写上吧 再说我也将localeCompare拼写错了,刚好改正 勿喷 感谢提醒

@muzea
Copy link

muzea commented Feb 7, 2018

我来贴个测试吧

var suite = new Benchmark.Suite;

suite.add('Intl', function() {
  new Intl.NumberFormat().format(123123);
})
.add('toLocaleString', function() {
  (123123).toLocaleString('en-US')
})
.add('replace', function() {
  String(123123).replace(/(^|\s)\d+/g, s => s.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
})
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });

输出

Intl x 29,401 ops/sec ±5.86% (46 runs sampled)
toLocaleString x 12,080 ops/sec ±15.81% (41 runs sampled)
replace x 1,254,177 ops/sec ±4.00% (46 runs sampled)
Fastest is replace

测试环境
chrome 64.0.3282.140
mbp 13 Early 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants