Skip to content
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

js常用工具方法备忘 #3

Open
39Er opened this issue May 8, 2017 · 0 comments
Open

js常用工具方法备忘 #3

39Er opened this issue May 8, 2017 · 0 comments

Comments

@39Er
Copy link
Owner

39Er commented May 8, 2017

1. 【Array】 reduce() 方法:

对累加器和数组的每个值 (从左到右)应用一个函数,以将其减少为单个值。
例1:

              let sum = [0, 1, 2, 3].reduce(function(acc, val) {
		  return acc + val;
		}, 0);
		console.log(sum);
		// 6
例2(TJ—only):
                //Return whitelisted properties of an object
		//筛选obj中特定的properties,reduce合并为一个新json对象返回
		module.exports = function(obj, keys){
		  obj = obj || {};
		  if ('string' == typeof keys) keys = keys.split(/ +/);
		  return keys.reduce(function(ret, key){
		    if (null == obj[key]) return ret;
		    ret[key] = obj[key];
		    return ret;
		  }, {});
		};

		var obj = {
		  name: 'tobi',
		  last: 'holowaychuk',
		  email: '[email protected]',
		  _id: '12345'
		};
		var user = only(obj, 'name last email');

【Object】Object.assign() 方法

用于将所有可枚举的属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

Object.assign(target, ...sources)
      参数:
        target 目标对象。
        sources (多个)源对象。
      返回值:目标对象。

Object.assign 方法只会拷贝源对象自身的并且可枚举的属性到目标对象身上。
针对深度拷贝,需要使用其他方法,因为 Object.assign() 拷贝的是属性值。假如源对象的属性值是一个指向对象的引用,它也只拷贝那个引用值。

【Object】Object.is() 方法

Object.is() 方法确定两个值是否是 相同的值。

Object.is(value1, value2);
参数
	value1 需要比较的第一个值。
	value2 需要比较的第二个值。
返回值
	一个布尔值指示两个参数是否相同的。

Object.is() 会在下面这些情况下认为两个值是相同的:

  • 两个值都是 undefined
  • 两个值都是 null
  • 两个值都是 true 或者都是 false
  • 两个值是由相同个数的字符按照相同的顺序组成的字符串
  • 两个值指向同一个对象
  • 两个值都是数字并且
    • 都是正零 +0
    • 都是负零 -0
    • 都是 NaN
    • 都是除零和 NaN 外的其它同一个数字

== 运算符会对它两边的操作数做隐式的类型转换(如果它们是不同类型的值的话),然后才进行相等性比较,(所以才会有类似 "" == false 为 true 的现象),但 Object.is 不会做这种类型转换。

严格相等运算符 === 也不会对操作数进行类型转换,但是它会把 -0 和 +0 这两个数值视为相同的,还会把两个 NaN 看成是不相等的。

Object.is(5,'5'); 	//false
5 == '5'			//true
5 === '5'			//false

Object.is(NaN,NaN);	//true
NaN === NaN			//false

Object.is(-0,+0);	//false
-0 === +0			//true
Repository owner locked and limited conversation to collaborators May 8, 2017
Repository owner unlocked this conversation May 8, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant