以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - JavaScript 代码题
26. 实现Object.assign()
function myAssign(target, ...sources) {
if (target === null || target === undefined) {
throw new TypeError('Cannot convert undefined or null to object');
}
let to = Object(target);
sources.forEach((source) => {
if (source !== null && source !== undefined) {
for (let key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
to[key] = source[key];
}
}
}
});
return to;
}
此函数接收任意数量的参数,第一个参数是目标对象,后面的参数是源。它首先检查目标是否是 undefined 或 null。如果是,则抛出类型错误。然后它创建目标对象的副本以防止它被修改。然后迭代源对象,并将源对象中的所有属性复制到目标对象中。然后返回目标对象的副本。