gpt4 book ai didi

javascript - 无法使用深度差异 JavaScript 函数

转载 作者:行者123 更新时间:2023-12-03 04:03:54 25 4
gpt4 key购买 nike

我正在尝试在我的 angularJS 应用程序中使用 javascript 包。我已将引用添加到我的index.html

<script src="deep-diff-0.3.1.min.js"></script>

我在我的 Controller 中使用了这个例子:

var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};

var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};

var differences = diff(lhs, rhs);

但是当我尝试运行我的应用程序时,出现以下错误:

ReferenceError: diff is not defined

我尝试过指向所有不同的版本,并且我也尝试过通过 Bower 和 npm 进行安装

最佳答案

我认为你必须在你的代码中使用它:

var diff = require('deep-diff').diff;

您还可以使用以下函数进行深度比较。我使用它并且效果很好:

var deepDiffMapper = function () {
return {
VALUE_CREATED: 'created',
VALUE_UPDATED: 'updated',
VALUE_DELETED: 'deleted',
VALUE_UNCHANGED: 'unchanged',
map: function (obj1, obj2) {
if (this.isFunction(obj1) || this.isFunction(obj2)) {
throw 'Invalid argument. Function given, object expected.';
}

if (this.isValue(obj1) || this.isValue(obj2)) {
return {
type: this.compareValues(obj1, obj2),
data1: obj1,
data2: obj2
};
}

var diff = {};
for (var key in obj1) {
if (this.isFunction(obj1[key])) {
continue;
}

var value2 = undefined;
if ('undefined' != typeof (obj2[key])) {
value2 = obj2[key];
}

var m = this.map(obj1[key], value2);
diff[key] = m;
}

for (var key in obj2) {
if (this.isFunction(obj2[key]) || ('undefined' != typeof (diff[key]))) {
continue;
}

var m = this.map(undefined, obj2[key]);
diff[key] = m;
}

return diff;

},
compareValues: function (value1, value2) {
if (value1 === value2) {
return this.VALUE_UNCHANGED;
}
if ('undefined' == typeof (value1)) {
return this.VALUE_CREATED;
}
if ('undefined' == typeof (value2)) {
return this.VALUE_DELETED;
}

return this.VALUE_UPDATED;
},
isFunction: function (obj) {
return {}.toString.apply(obj) === '[object Function]';
},
isArray: function (obj) {
return {}.toString.apply(obj) === '[object Array]';
},
isObject: function (obj) {
return {}.toString.apply(obj) === '[object Object]';
},
isValue: function (obj) {
return !this.isObject(obj) && !this.isArray(obj);
},
changed: function (m) {

if (!this.isObject(m))
return false;

var c = false;
var found = false;

angular.forEach(m, function (value, key) {

if (!found) {

if (deepDiffMapper.isObject(value))
c = (c || deepDiffMapper.changed(value));
else if (key == "type") {
c = (c || (value == "updated") || (value == "created") || (value == "deleted"));
}

if (c) {
found = true;
}
}
});

return c;
}
}
}();

关于javascript - 无法使用深度差异 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44653431/

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