dispatchMessage 和关联数组
我在将关联数组传递给注入脚本时遇到问题。
Global.html
var settings = new Array();
settings["accountID"] = safari.extension.settings.getItem("accountID");
settings["accountName"] = safari.extension.settings.getItem("accountName");
settings["accountEmail"] = safari.extension.settings.getItem("accountEmail");
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("settingsArray", settings);
script.js
switch (msgEvent.name) {
case "settingsArray":
var settings = new Array();
settings = msgEvent.message;
console.log("accountID: " + settings["accountID"]);
break;
当我使用“普通”数组时,它工作得很好!
但是当提供关联数组时,我总是得到调用时显示“未定义”,例如。 settings["accountID"]
有人知道出了什么问题吗?
I have a problem delivering assiciative arrays to an injected script.
Global.html
var settings = new Array();
settings["accountID"] = safari.extension.settings.getItem("accountID");
settings["accountName"] = safari.extension.settings.getItem("accountName");
settings["accountEmail"] = safari.extension.settings.getItem("accountEmail");
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("settingsArray", settings);
script.js
switch (msgEvent.name) {
case "settingsArray":
var settings = new Array();
settings = msgEvent.message;
console.log("accountID: " + settings["accountID"]);
break;
When I do it with "normal" arrays, it works fine!
But when delivering associative arrays, I always get "undefined" when calling eg. settings["accountID"]
Does anyone have an idea what's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你应该使用对象时,你却使用了数组。
您没有必要使用字符串形式的属性访问。
如果属性名称不是有效的 JavaScript 标识符,则在获取/设置属性值时只需使用方括号表示法(例如
foo["holy!*#$! it Works"] = true
)或者如果您需要从变量构造属性名称(例如foo["account"+n] = "active";
)。您正在创建新对象然后把它们扔掉。
You're using arrays when you should be using objects.
You are unnecessarily using the string form of property access.
You only need to use the bracket notation when getting/setting property values if the property name is not a valid JavaScript identifier (e.g.
foo["holy!*#$! it works"] = true
) or if you need to construct the property name from a variable (e.g.foo["account"+n] = "active";
).You are creating new objects and then throwing them away.