假設我們有
x = {a:65, b:634, c:74};
y = {o:453, e:5342, g:543}
z = {o:453, e:5342, b:543}
// Doing this should be okay
const both = {...x, ...y}
// However, when doing this:
const both = {...x, ...z}
我需要它來顯示一些錯誤,例如“無法重新分配屬性 b”或其他什么,只是不要讓它編譯。有什么建議么?
uj5u.com熱心網友回復:
這是一個帶有 n 個引數的解決方案:
function combineNoOverwrite(...args) {
return args.reduce((acc, cur) => {
for (var key in cur) {
if (cur.hasOwnProperty(key) && !acc.hasOwnProperty(key)) {
acc[key] = cur[key];
} else {
throw new Error(`key ${key} cannot be re-assigned`);
}
}
return acc;
});
}
uj5u.com熱心網友回復:
最簡單的方法是制作一個簡單的實用程式函式..
您可以獲取每個密鑰,并使用包含來確保密鑰不存在于其他密鑰中。
例如。
const x = {a:65, b:634, c:74};
const y = {o:453, e:5342, g:543};
const z = {o:453, e:5342, b:543};
function join(a,b) {
const ak = Object.keys(a);
const bk = Object.keys(b);
for (const k of bk)
if (ak.includes(k))
throw new Error(`key ${k} cannot be re-assigned`);
return {...a, ...b};
}
console.log(join(x, y));
console.log(join(x, z));
uj5u.com熱心網友回復:
您可以使用以下內容。
function combine(x, y) {
const array = Object.keys(x).concat(Object.keys(y))
if (array.length != [...new Set(array)].length) {
console.error("Error: Duplicate Key")
return
}
return {...x, ...y}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/504832.html
標籤:javascript 打字稿
上一篇:如何過濾字典?
