JSON.stringify和angular.toJson无法正常工作

时间:2016-05-24 19:11:15

标签: javascript angularjs json

所以我必须反对:

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}

     

模型{"轻":真,"新":真,"可用":假}

     

他们是不同的假

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

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

我得到了同样的结果。

有谁知道为什么?

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题