About JSON.stringify ()

var students = {};

students.app = "nmm"; 
students.aps = "nms"; 
students.ape = "jju"; 
var json = JSON.stringify(students,switchUpper); 
function switchUpper(key, value) { 
        if (typeof value=="string") {
             return value; 
        }
         
} 
    console.log(json

A rookie asks for help! When the second argument of the JSON.stringify () method is a function. Who passed in the two parameters in the function, and is key app,aps,ape?? Is value "nmm","nms","jju"?"? If so, why is the condition reached in the function? the final undefined?? returned by json

Aug.29,2021

if replacer is a function, JSON.stringify calls the function, passing in the key and value of each member. Use the return value instead of the original value. Excludes members if this function returns undefined,. The key of the root object is an empty string: ".

the key of the root node is ' empty string value is this object

{
    name:1,
    children:{
        name:2
    }
}

for example, the switchUpper traversal order
is
1, respectively. Key: ', value: {name:1,children: {name:2}}
2. Key: name , value: 1
3. Key: children , value: {name:2}
4. Key: name , Value: 2
his child objects are deleted when undefined is returned, for example, 1 , when undefined 234 is returned,
is not executed
so the first time you enter value is students , so if not the string returns undefined , then there is no

.

I'll answer

Who passed in the two parameters in the
function

Let's start with a simple example of a callback function

function stringify(obj,fn){
    Object.keys(obj).forEach(key=>{
        fn(key,obj[key])
    })
}
var a = {foundation: "Mozilla", model: "box"}
var s = function(key,value) {console.log(key,value)}
stringify(a,s) //foundation Mozilla model box
The inner part of the

callback function is generally implemented like this. It can be seen that the parameters of the callback function fn are passed by the execution function stringify

.
Menu