为什么我在 JSON.stringify(value, replacer) 中的替换函数在 Angular 应用程序中没有收到密钥?
Why my replacer function in JSON.stringify(value, replacer) doesn't receive keys in Angular application?
尝试按照此处的说明实施 JSON.stringify:Hide certain values in output from JSON.stringify() 并从序列化中排除某些字段,但它不起作用。
例如,在我的控制器中,我有以下代码:
.controller('ExampleController', ['$scope', function($scope) {
$scope.event = {
id:1,
title: 'event title',
users: [{
id: 1,
name: 'Anatoly'
},{
id: 2,
name: 'Roman'
}],
private1: 1,
private2: 2
};
var replacer = function(key, value){
console.log(key);
};
$scope.stringified1 = JSON.stringify($scope.event, replacer);
// $scope.stringified = JSON.stringify($scope.event, ['id','title','users','name']);
}]);
为什么 console.log(key)
什么都不打印?调用函数本身,但 key
参数为空。
我在这里做过 plunker:http://plnkr.co/edit/U6ZcIuPVr5RzMIBl8X6c?p=preview
我正在使用 Angular 1.4.9 和 Chrome 48.0.2564.116
P.S。我已经使用传递的数组完成了此功能并且它可以工作,但是使用函数可以提供更大的灵活性所以我想了解为什么它不起作用。
好的,这里的手册并不清楚:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify 但是因为 replacer
以递归方式调用它应该 return 被调用的对象,根对象本身太:
Initially it gets called with an empty key representing the object
being stringified
你应该return这个对象,如果你return什么都不做,它就不会被调用这个对象的其他属性
and it then gets called for each property on the object or array
being stringified
所以,感谢@charlietfl 的提示,我修复了它,你可以在这里看到修复的 plunker:http://plnkr.co/edit/a3S8yGx78b7vJSKwORw5?p=preview
尝试按照此处的说明实施 JSON.stringify:Hide certain values in output from JSON.stringify() 并从序列化中排除某些字段,但它不起作用。
例如,在我的控制器中,我有以下代码:
.controller('ExampleController', ['$scope', function($scope) {
$scope.event = {
id:1,
title: 'event title',
users: [{
id: 1,
name: 'Anatoly'
},{
id: 2,
name: 'Roman'
}],
private1: 1,
private2: 2
};
var replacer = function(key, value){
console.log(key);
};
$scope.stringified1 = JSON.stringify($scope.event, replacer);
// $scope.stringified = JSON.stringify($scope.event, ['id','title','users','name']);
}]);
为什么 console.log(key)
什么都不打印?调用函数本身,但 key
参数为空。
我在这里做过 plunker:http://plnkr.co/edit/U6ZcIuPVr5RzMIBl8X6c?p=preview
我正在使用 Angular 1.4.9 和 Chrome 48.0.2564.116
P.S。我已经使用传递的数组完成了此功能并且它可以工作,但是使用函数可以提供更大的灵活性所以我想了解为什么它不起作用。
好的,这里的手册并不清楚:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify 但是因为 replacer
以递归方式调用它应该 return 被调用的对象,根对象本身太:
Initially it gets called with an empty key representing the object being stringified
你应该return这个对象,如果你return什么都不做,它就不会被调用这个对象的其他属性
and it then gets called for each property on the object or array being stringified
所以,感谢@charlietfl 的提示,我修复了它,你可以在这里看到修复的 plunker:http://plnkr.co/edit/a3S8yGx78b7vJSKwORw5?p=preview