gpt4 book ai didi

javascript - jQuery比较两组对象并获取值差异的位置

转载 作者:行者123 更新时间:2023-11-30 10:08:22 25 4
gpt4 key购买 nike

这个网站上有很多关于比较两组 JavaScript 对象的问题,但我找不到我想要实现的目标。

我有如下两组对象。

var players = [
{ "id" : "45783",
"r3" : "DED" },
{ "id" : "54762",
"r3" : "DEDCCCCDDDDC" },
{ "id" : "78903",
"r3" : "DEDCDBDDDDDC"}
]
var oldPlayers = [
{ "id" : "45783",
"r3" : "DE" },
{ "id" : "54762",
"r3" : "DEDCCCCDDDD" },
{ "id" : "78903",
"r3" : "DEDCDBDDDDD"}
]

我想比较上面的数据并找到 var players 中的确切位置,“r3”值与 oldPlayers 不同。

例如,

players ---- "r3" : "DED"
oldPlayers - "r3" : "DE"

以上数据的不同之处在于假设数字从0开始,玩家在[2]处的 Angular 色位置有额外的D。

我有每个循环,我打算获得这个位置,但我不知道如何让它工作。

var isOldPlayers = false;

// check if oldPlayers exists
if(oldPlayers != undefined && oldPlayers != ''){
isOldPlayers = true;
}

$.each(players,function(i,v){

if(isOldPlayers){
var oldScores = oldPlayers[i]['r3'];
var newScores = this['r3'];

if(newScores != oldScores){
// how can I get the exact location of the difference?
}

}
});

最佳答案

使用数组可能会加快速度。如果字符串将包含与上面大部分相同的字符,这将是一个好方法。这对你有用吗?

var dIdx = [v['r3'], oldPlayers[i]['r3']].sort()[0].length;

// ["DED", "DE"].sort() --> ["DE", "DED"];
// ["DE", "DED"][0] --> "DE"
// "DE".length --> 2

// "DED" differs from "DE" at index 2

或者如果您需要差异本身,您可以这样做:

var scores = [v['r3'], oldPlayers[i]['r3']].sort(),
diff = scores[1].substr(scores[0].length);

编辑

明确一点,您不需要将“players”对象设为数组。单击图像进行演示。

enter image description here

var players = [
{ "id" : "45783",
"r3" : "DED" },
{ "id" : "54762",
"r3" : "DEDCCCCDDDDC" },
{ "id" : "78903",
"r3" : "DEDCDBDDDDDC"}
],
oldPlayers = [
{ "id" : "45783",
"r3" : "DE" },
{ "id" : "54762",
"r3" : "DEDCCCCDDDD" },
{ "id" : "78903",
"r3" : "DEDCDBDDDDD"}
];
var desc = '';
$.each(players, function(i, v) {
var dIdx = [v['r3'], oldPlayers[i]['r3']].sort()[0].length;

desc += '<span class="h">' + v['r3'] + '</span> ' +
'and <span class="h">' + oldPlayers[i]['r3'] + '</span> ' +
'differ at index: <span class="hg">' + dIdx + '</span><br><br>';
});
$('body').html(desc);

关于javascript - jQuery比较两组对象并获取值差异的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27932334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com