gpt4 book ai didi

javascript - 将 javascript 函数作为对象中的键是否完全有效?

转载 作者:可可西里 更新时间:2023-11-01 02:21:37 25 4
gpt4 key购买 nike

将 javascript 函数作为对象中的键是否完全有效?

以下是可行的,但我不确定它是否 100%(ecma 或任何管理它的机构)兼容

var f = function(){

};

var obj = {};

obj[f] = "a";


console.log(obj[f]);

最佳答案

它看起来工作正常,但它可能不会像您预期的那样工作。

当用作键时,该函数被转换为字符串:

var f = function(a) { return a; };
var obj = {};
obj[f] = 'abc';
console.log(JSON.stringify(obj));
//"{"function (a) { return a; }":"abc"}"
console.log(f.toString());
//"function (a) { return a; }"
var f2 = function (a) { return a; };
console.log(obj[f2]);
//"abc"

因此,函数 f 和 f2 是不同的对象,但在转换为字符串时它们是相同的。

关于javascript - 将 javascript 函数作为对象中的键是否完全有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15220292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com