let a = { a: '', b: '' },
b = { a: 1, b: 4, c: 3 };
想要得到 a={a:1,b:4};
有一步到位的方法吗? 像 Object.assign 类似的方法
let a = { a: '', b: '' },
b = { a: 1, b: 4, c: 3 };
想要得到 a={a:1,b:4};
有一步到位的方法吗? 像 Object.assign 类似的方法
没看明白,为什么属性a里,一个是空,一个是1,最后得到的是1?
是这个意思吗?比如有多个对象A, B, C,只要其中一个对象里没有这个属性,那么最后得到的这个对象里,就没这个属性?
比如上面的:
let a = { a: '', b: '' },
b = { a: 1, b: 4, c: 3 };
对象a里没有c属性,所以最后得到的数据也没有c属性?
可以参考下用es5实现Object.assign的方法: Object.assign
if (typeof Object.assignless != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assignless", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = new Object();
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(target, nextKey) && Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
由于只考虑最少的, 所以循环一遍就可以, 调用的时候Object.assignless(a, b);
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读