( 译、持续更新 ) JavaScript 上分小技巧(四)

后续如有内容,本篇将会照常更新并排满15个知识点,以下是其他几篇译文的地址:

第一篇地址:( 译、持续更新 ) JavaScript 上分小技巧(一)

第二篇地址:( 译、持续更新 ) JavaScript 上分小技巧(二)

第三篇地址:( 译、持续更新 ) JavaScript 上分小技巧(三)

#49 - JS中最简单的方式获取时间戳

我们经常需要获取时间戳进行计算,有好几种方式来获取时间戳,目前最简单也是最快的方法是:

const timestamp = Date.now();

或者

const timestamp = new Date().getTime();

获取具体时间 yyyy-mm-dd 的时间戳,我们可以通过给Date构造函数传入一个参数,例如:

const timestamp = new Date('2012-06-08').getTime()

也可以在声明日期对象时添加一个+符号,如下所示:

const timestamp = +new Date()

或者获取指定日期的时间戳

const timestamp = +new Date('2012-06-08')

引擎中调用了Date对象valueOf方法,返回一元运算符"+"配合返回的值调用toNumber()。更多详细说明请查看以下链接:

Date.prototype.valueOf 
一元运算符"+" 
toNumber() 

#48 - 内置函数reduce的用法
正如文档所写,reduce()方法应用一个函数以针对数组的值(从左到右),以减至一个值。
reduce()
reduce()方法接收两个参数(M:mandatory,O:options):
 (M)一个回调函数,用于处理与先前的计算结果和下一个元素。
 (O)被作为回调函数的第一个调用的参数的初始值。
所以,我们来看看普通用法,后面再来一个更先进的。
常见的用法(积累,连接)
假如我们在购物,并且购物车足够满,让我们计算价格总和:

// 现在的价格var items = [{price: 10}, {price: 120}, {price: 1000}];// reducer函数var reducer = function add(sumSoFar, nextPrice) { return sumSoFar + nextPrice.price; };// 处理...var total = items.reduce(reducer, 0);
console.log(total); // 1130

函数的可选参数在一般情况下是0,它可以是个对象,也可以是个数组。
现在,我们获得一张20元的代金券:

var total = items.reduce(reducer,-20);
console.log(total); // 1110

高端用法(组合)
落后的思想是将reducers分别写成单独的功能,并最终计算出一个新的reducers的功能。
为了说明这一点,让我们创建一个对象与一些能够计算不同货币美元的总价格的reducers功能。

var reducers = {
  totalInDollar: function(state, item) {
    state.dollars += item.price;    return state;
  },
  totalInEuros : function(state, item) {
    state.euros += item.price * 0.897424392;    return state;
  },
  totalInYen : function(state, item) {
    state.yens += item.price * 113.852;    return state;
  },
  totalInPounds : function(state, item) {
    state.pounds += item.price * 0.692688671;    return state;
  }  // 更多...};

然后,我们创建一个新的功能:
 · 负责应用reduce的各部分功能。
 · 将返回一个新的回调函数。

var combineTotalPriceReducers = function(reducers) {  return function(state, item) {    return Object.keys(reducers).reduce(      function(nextState, key) {
        reducers[key](state, item);        return state;
      },
      {}      
    );
  }
};

现在,让我们看看怎么使用这个:

var bigTotalPriceReducer = combineTotalPriceReducers(reducers);var initialState = {dollars: 0, euros:0, yens: 0, pounds: 0};var totals = items.reduce(bigTotalPriceReducer, initialState);
console.log(totals);/*Object {dollars: 1130, euros: 1015.11531904, yens: 127524.24, pounds: 785.81131152}*/

我希望这个方法能够在你所需要的时候给你提供一个reduce使用的思路。
#47 - 基本声明
下面是javascript中声明变量的不同方式。console.log能够很好的解释这里将发生什么。

var y, x = y = 1 //== var x; var y; x = y = 1console.log('_> 1:', `x = ${x}, y = ${y}`)// 将会打印//_> 1: x = 1, y = 1

首先,我们设置两个变量,在这里没更多的操作。

;(() => { 
  var x = y = 2 // == var x; y = 2;
  console.log('2.0:', `x = ${x}, y = ${y}`)
})()
console.log('_> 2.1:', `x = ${x}, y = ${y}`)// 将会打印//2.0: x = 2, y = 2//_> 2.1: x = 1, y = 2

正如你所见的,这里的代码只改变了全局的y,因为我们没有在闭包中声明变量。

;(() => { 
  var x, y = 3 // == var x; var y = 3;
  console.log('3.0:', `x = ${x}, y = ${y}`)
})()
console.log('_> 3.1:', `x = ${x}, y = ${y}`)// 将会打印//3.0: x = undefined, y = 3//_> 3.1: x = 1, y = 2

现在我们通过var来声明变量。这意味着他们只存在封闭的语境中。

;(() => { 
  var y, x = y = 4 // == var x; var y; x = y = 4
  console.log('4.0:', `x = ${x}, y = ${y}`)
})()
console.log('_> 4.1:', `x = ${x}, y = ${y}`)// 将会打印//4.0: x = 4, y = 4//_> 4.1: x = 1, y = 2

这两个变量都通过var声明并且只会给定了值。因为local>global,所以x和y在本地封闭语境中,意味着全局的x和y没做改变。

x = 5 // x = 5console.log('_> 5:', `x = ${x}, y = ${y}`)// 将会打印//_> 5: x = 5, y = 2

这最后一行是明确的。
更多的变量相关信息:MDN
#46 - js纯粹的检测文档加载完毕
使用readyState以跨浏览器的方式来检测javascript文档是否加载。

if (document.readyState === 'complete') {    // 页面已经完全加载}

你能够检查文档是否加载...

let stateCheck = setInterval(() => {    if (document.readyState === 'complete') {
    clearInterval(stateCheck);     // document ready  }
}, 100);

或者使用onreadystatechange...

document.onreadystatechange = () => {  if (document.readyState === 'complete') {   // document ready  }
};

使用document.readyState === 'interactive'检测DOM是否ready。
### 2016-02-18 更新 ###

转载于:https://my.oschina.net/yeshou/blog/617303

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值