我正在编写一个将对象或数组作为参数的函数,我想为其创建一个新的空副本,并使用原始对象的转换数据填充它。
我想知道是否有一种方法可以简单地创建这个新对象/数组,而不必测试它是什么类型并采取适当的行动。
目前“长”的路是:
const transf = (thing) => {
if (typeof(thing) === 'array') {
const new = []
} else {
const new = {}
}
}
我希望有一个很好的“内置”方式我可以做类似的事情:
const transf = (thing) => {
const new = thing.emptyCopy()
}
我看过 Object.create
但它总是生成一个 object
(即使 prototype
是一个 array
), typeof
返回一个字符串,不能与例如新的
等
有没有一种简写的方法可以做到这一点,还是我运气不好?
最佳答案
您可以使用 thing
的 constructor
属性。并且不要使用 new
作为变量名。
const transf = (thing) => {
const newelm = new thing.constructor()
}
演示:
const transf = (thing) => {
return new thing.constructor()
}
console.log(transf(['arra']))
console.log(transf({key:'value'}))
关于javascript - 基于现有对象/数组创建一个空对象/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338887/