JavaScript/拷贝:修订间差异
来自康健生活
无编辑摘要 |
|||
| (未显示同一用户的4个中间版本) | |||
| 第33行: | 第33行: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
测试: | 测试: | ||
{{ | {{Double-columns|<syntaxhighlight | ||
lang="javascript"> | lang="javascript"> | ||
const bar = {biz: 1} | const bar = {biz: 1} | ||
| 第43行: | 第43行: | ||
1 | 1 | ||
5 | 5 | ||
</pre>}}}} | |||
=== 防栈溢出函数 === | |||
<syntaxhighlight lang="javascript"> | |||
function cloneLoop(x) { | |||
const root = {}; | |||
// 栈 | |||
const loopList = [ | |||
{ | |||
parent: root, | |||
key: undefined, | |||
data: x, | |||
} | |||
]; | |||
while(loopList.length) { | |||
// 深度优先 | |||
const node = loopList.pop(); | |||
const parent = node.parent; | |||
const key = node.key; | |||
const data = node.data; | |||
// 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 | |||
let res = parent; | |||
if (typeof key !== 'undefined') { | |||
res = parent[key] = {}; | |||
} | |||
for(let k in data) { | |||
if (data.hasOwnProperty(k)) { | |||
if (typeof data[k] === 'object') { | |||
// 下一次循环 | |||
loopList.push({ | |||
parent: res, | |||
key: k, | |||
data: data[k], | |||
}); | |||
} else { | |||
res[k] = data[k]; | |||
} | |||
} | |||
} | |||
} | |||
return root; | |||
}</syntaxhighlight> | |||
{{Unknown|dobeco}} | |||
=== 其他 === | |||
{{Double-columns|<syntaxhighlight | |||
lang="javascript"> | |||
function copyObject(orig) { | |||
var copy = Object.create(Object.getPrototypeOf(orig)); | |||
copyOwnPropertiesFrom(copy, orig); | |||
return copy; | |||
} | |||
function copyOwnPropertiesFrom(target, source) { | |||
Object | |||
.getOwnPropertyNames(source) | |||
.forEach(function (propKey) { | |||
var desc = Object.getOwnPropertyDescriptor(source, propKey); | |||
Object.defineProperty(target, propKey, desc); | |||
}); | |||
return target; | |||
} | |||
var obj = { | |||
name: 'Jack', | |||
age: '32', | |||
job: 'developer' | |||
}; | |||
var obj2 = copyObject(obj); | |||
console.log(obj2); | |||
obj.age = 39; | |||
obj.name = 'Tom'; | |||
console.log(obj); | |||
console.log(obj2); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
> Object { name: "Jack", age: "32", job: "developer" } | |||
> Object { name: "Tom", age: 39, job: "developer" } | |||
> Object { name: "Jack", age: "32", job: "developer" } | |||
</pre>}}}} | |||
{{Unknown|dobeco}} | |||
=== 函数拷贝 === | |||
{{Double-columns|<syntaxhighlight | |||
lang="javascript"> | |||
const foo = x => x + 1 | |||
const bar = eval(foo.toString())(1) | |||
console.log(bar) | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
2 | |||
</pre>}}}} | </pre>}}}} | ||
== 浅拷贝 == | == 浅拷贝 == | ||