Javascript:无法使用函数数组初始化对象属性

时间:2022-07-05 21:28:56

I'm stuck on this simple one :

我坚持这个简单的一个:

var myfunc1 = function() {
    console.log('just a function');
};

var myfunc2 = function() {
    console.log('just another function');
};

var myobj = {
    id : 1,
    desc : 'an object',
    funz : [myfunc1, myfunc2]
};

console.log(JSON.stringify(myobj));

=> output

=>输出

/usr/local/bin/node lab.js
{"id":1,"desc":"an object","funz":[null,null]}

I was hopping to have something like :

我跳得像是这样的:

{"id":1,"desc":"an object","funz":[Function,Function]}

What do I miss ?

我错过了什么?

2 个解决方案

#1


2  

Found on the Mozilla Developer Network:

在Mozilla开发者网络上找到:

"If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array)."

“如果在转换过程中遇到未定义,函数或符号,则将其省略(当在对象中找到它时)或者删除为null(当它在数组中找到时)。”

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

#2


1  

Turns out functions are omitted in JSON.stringify

原来在JSON.stringify中省略了函数

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

如果未定义,则在转换期间遇到函数或符号,或者省略它(当它在对象中找到时)或者删除为null(当它在数组中找到时)。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

You could do:

你可以这样做:

var myobj = {
    id : 1,
    desc : 'an object',
    funz : [String(myfunc1), String(myfunc2)]
};

to get what you want.

得到你想要的。

#1


2  

Found on the Mozilla Developer Network:

在Mozilla开发者网络上找到:

"If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array)."

“如果在转换过程中遇到未定义,函数或符号,则将其省略(当在对象中找到它时)或者删除为null(当它在数组中找到时)。”

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

#2


1  

Turns out functions are omitted in JSON.stringify

原来在JSON.stringify中省略了函数

If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

如果未定义,则在转换期间遇到函数或符号,或者省略它(当它在对象中找到时)或者删除为null(当它在数组中找到时)。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

You could do:

你可以这样做:

var myobj = {
    id : 1,
    desc : 'an object',
    funz : [String(myfunc1), String(myfunc2)]
};

to get what you want.

得到你想要的。