let traveler = [{
timestamp: 'qualia',
firstname: 'unborn',
lastname: 'child',
location: 'null'
},
{
timestamp: 1000,
firstname: 'Olivia',
lastname: 'Kirshner',
location: 'Titan'
},
{
timestamp: 1001,
firstname: 'James',
lastname: 'Cole',
location: 'Emerson Hotel'
}
]
// function noerror(splinter = traveler[0]) {
// return [{firstname, lastname}] = splinter
// }
function restructure(time) {
// if no array is returned on the lookup, and the value flags as undefined in restructure()
let missingLink = traveler[0]
let tempArray = traveler
.filter((item) => item.timestamp === time)
try {
if (tempArray.length === 0) {
return {
firstname,
lastname
} = missingLink
}
return [{
firstname,
lastname
}] = tempArray
} catch (e) {
// e instanceof TypeError // boolean error type check
switch (e.name) {
case 'TypeError':
console.error(`Could not complete your request: ${e.message}`);
return {
firstname,
lastname
} = missingLink
default:
break;
}
}
}
// the logging statement breaks the code with a ReferenceError: 'timestamp' is not defined
// does that mean destructuring enforces type safety???
// console.log(traveler)
[{timestamp, firstname, lastname, location}] = traveler
restructure(1001)
console.log(`firstname: ${firstname}, lastname: ${lastname}`)
restructure(100)
console.log(`firstname: ${firstname}, lastname: ${lastname}`)
restructure(1000)
lastname = 'Redforester' // temp assignment
console.log(`firstname: ${firstname}, lastname: ${lastname}`)
restructure(1000)
// console.log(traveler)
[{timestamp, firstname, lastname, location}] = traveler
console.log(`timestamp ${timestamp}, firstname ${firstname}, lastname ${lastname}, location ${location}`);
解构强制类型安全性是否解释了为什么如果包含console.log(traveler)
时此代码不起作用?
您仍可以在发生解构的对traveler
的函数调用之后记录对象restructure()
,但除非在进行任何解构操作之前完成对变量restructure()
的解构分配,在旅行者对象上,它将出错。换句话说,必须在对对象进行任何其他解构之前,timestamp
才能显示:[{timestamp, firstname, lastname, location}] = traveler
。
将日志记录语句保留在第70行的结果如下:
发生异常:ReferenceError
ReferenceError:未在对象上定义时间戳。
不幸的是,在这里的代码控制台中,结果没有像在vscode中一样显示出来。
最终,我正在寻找一种在一段时间后引用traveler
中的每个键的方法,而不必将所有变量解构为在其他解构方案中使用该对象的前提。
我也对与将键/值对动态添加到同一对象中的对象感到好奇。例如,如果类型不匹配其他“记录”,以后添加键/值对是否会破坏结构?