【问题标题】:JSON.stringify and angular.toJson not working as expectedJSON.stringify 和 angular.toJson 没有按预期工作
【发布时间】:2016-05-24 19:11:14
【问题描述】:

所以我要反对:

var productCopy = {
    "light": true,
    "new": true,
    "available": false
};

var model = {
    "light": true,
    "new": true,
    "available": false
};

我需要比较两者,所以我这样做了:

// Create our 2 strings
var productCopyString = JSON.stringify(productCopy);
var modelString = JSON.stringify(model);

然后我这样做了:

return modelString !== productCopyString;

但它不起作用。所以我做了一个这样的console.log:

console.log('productCopy', productCopyString);
console.log('model', modelString);
console.log('are they different', modelString !== productCopyString)

然后返回:

productCopy {"light":true,"new":true,"available":false}

模型 {"light":true,"new":true,"available":false}

它们有什么不同吗

这很奇怪,所以我这样做了:

var productCopyString = angular.toJson(productCopy);
var modelString = angular.toJson(model);

我得到了同样的结果。

有人知道为什么吗?

【问题讨论】:

  • 我不知道你在期待什么。字符串相等,所以!== 运算符给出false。
  • 什么不起作用?我在 JSBin 中运行了它,结果符合预期。 jsbin.com/voqagoqawa/edit?js,console
  • 有什么问题,你在期待什么,两个字符串是一样的,比较时在两者上应用了一个不相等的运算符,结果是假的,意思是,两者都是一样的,所以 what很奇怪?
  • are they different false 这是一个真实的声明。

标签: javascript angularjs json


【解决方案1】:

在 Javascript 中,如果两个字符串具有相同的数据,则它们等于 ===。

例如:'{"light":true,"new":true,"available":false}' === '{"light":true,"new":true,"available":false}'

注意:在 Java 等其他语言中,两个字符串相等 == 是指它们引用同一个实例。在这种情况下,具有相同数据的两个字符串不会是==。

【讨论】:

  • 是的,我知道我在做一些愚蠢的事情,一直盯着代码看太久,我看不到树木的树林
猜你喜欢
  • 2015-09-23
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 2013-07-07
  • 2012-12-05
  • 2017-05-22
  • 2019-07-28
相关资源
最近更新 更多