如下,
1.hasOwnProperty(id)判断有没有id, 与let id in first 里的id,有关系吗 ?
2.如果result[id]已经存在,则不赋值.实际举例:
更正:
first = [1,2,3]
second = [3,4,5]
执行程序后,
console.log(result)输出如下:
{ '0': 1, '1': 2, '2': 3 }
function extend<T, U>(first: T, second: U): T & U {
let result = {} as T & U
for (let id in first) { //
result[id] = first[id] as any
}
for (let id in second) { //
if (!result.hasOwnProperty(id)) {
result[id] = second[id] as any
}
}
return result
}
###
1、没懂你说的“有关系”指的是什么?hasOwnPorperty
只检测非继承成员,而 for ... in
是包含继承成员的(继承属性你可以近似理解为原型链上的成员)。
2、你这段代码的用途是聚合 first
和 second
两个对象里的成员,并且如果相同的 key 同时存在于 first
和 second
两者中,则以 first
的为准。有点儿像反过来的 Object.assign()
。
补充回答见评论区。