我對此進行了很多搜索,但沒有找到任何可以讓我了解我的問題的資訊:
我有這個代碼:
let array1 = ["a", "b", 3, {
p1: 'hola'
}, "c", "d"],
array2 = [1, 2, {
p1: 'adios'
}],
result = [],
i, l = Math.min(array1.length, array2.length);
for (i = 0; i < l; i ) {
if (typeof array1[i] === 'object' && typeof array2[i] === 'object') {
result.push(array2[i], ...(JSON.stringify() === JSON.stringify() ?
[] :
[array1[i]]
));
} else {
result.push(array2[i], array1[i]);
}
}
result.push(...array1.slice(l), ...array2.slice(l));
console.log(result);
我已經根據建議修改了代碼,現在代碼執行以下操作:
我們有兩個陣列;
array1 = ["a", "b", 3, {p1: 'hello'},"c", "d"] array2 = [1, 2, {p1: 'hello'}]
現在的結果是基于代碼:
結果: [1, 'a', 2, 'b', {p1: 'hello'}, 3, {p1: 'hello'}, 'c', 'd']
這個作業很好,因為我不想省略兩個陣列之間不同索引的物件,現在的問題是當兩個陣列中的物件在相同的索引中時,這個代碼;
array1 = ["a", "b", {p2: 'goodbye'},"c", "d"] array2 = [1, 2, {p1: 'hello'}]
結果:[1,'a',2,'b',{p1:'你好'},'c','d']
這是我現在的問題,我想要的是,當兩個陣列上的相同索引中有物件時,比較物件的屬性并且相同跳過第一個陣列物件并將第二個傳遞給最終陣列,但是如果屬性不一樣,將物件的屬性合二為一,這是我想要的理想結果:
array1 = ["a", "b", {p2: 'goodbye'},"c", "d"] array2 = [1, 2, {p1: 'hello'}]
結果:[1,'a',2,'b',{p1:'你好',p2:'再見'},'c','d']
uj5u.com熱心網友回復:
我認為這就是你所追求的。
let array1 = ['a', 'b', { p2: 'goodbye' }, 'c', 'd'];
let array2 = [1, 2, { p1: 'hello' }];
let result = [];
for (let i = 0; i < Math.max(array1.length, array2.length); i ) {
if (typeof array1[i] == 'object' && typeof array2[i] == 'object') {
result.push({ ...array2[i], ...array1[i] });
} else {
array2[i] && result.push(array2[i]);
array1[i] && result.push(array1[i]);
}
}
console.log(result);
uj5u.com熱心網友回復:
您可以比較這些專案,如果相同則省略第二個專案。
let array1 = ["a", "b", {p1: 'hello world'},"c", "d"],
array2 = [1, 2, {p1: 'hello world'}],
result = [],
i, l = Math.min(array1.length, array2.length);
for (i = 0; i < l; i ) {
result.push(array2[i], ...(JSON.stringify() === JSON.stringify()
? []
: [array1[i]]
));
}
result.push(...array1.slice(l), ...array2.slice(l));
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351781.html
標籤:javascript 数组 目的
