问题描述
$ p
$ b
chrome.storage.local.get('sizePref',function(items){//获取大小来自存储的偏好
var sizePref2 = items.sizePref.tops; //将大小设置为var
console.log(您可以得到这个+ sizePref2)
});
然而,当我尝试使它成为一个函数时
function getSize(itemSize){
chrome.storage.local.get('sizePref',function(items){//从存储区获取大小首选项
var sizePref = items.sizePref.itemSize;
return(sizePref);
});
}
var mySize = getSize(tops);
console.log(您要查找的大小是+ mySize)
它说tops是未定义的。
当属性名称在变量中时,使用括号语法。所以,而不是这样:
items.sizePref.itemSize
$ p
$ b你使用这个:
items.sizePref [itemSize]
另外,不能从异步中同步返回一个值回电话。这个逻辑是错误的。所以,你不能做一个函数
getSize()
来返回结果。在getSize()
已经返回之后的一段时间内,结果将不可用。您必须将回调传递给getSize()
或让getSize()
返回承诺。函数getSize(itemSize){
返回新的Promise(函数(解析){
chrome.storage.local。 get('sizePref',function(items){//从存储中获取大小首选项
resolve(items.sizePref [itemSize]);
});
}
getSize(whatever)。then(function(result){
//在此使用结果的代码
});
This works
chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage var sizePref2 = items.sizePref.tops; // Set size to a var console.log("You can get this " + sizePref2) });
However, when I try to make it a function
function getSize(itemSize) { chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage var sizePref = items.sizePref.itemSize; return (sizePref); }); } var mySize = getSize(tops); console.log("This size that u are looking for is " + mySize)
it says "tops" is undefined.
解决方案When the property name is in a variable, you use the bracket syntax. So, instead of this:
items.sizePref.itemSize
you use this:
items.sizePref[itemSize]
In addition, you cannot return a value synchronously from an async callback. That logic is just wrong. So, you can't make a function
getSize()
that will return the result. The result will not be available until some time LATER aftergetSize()
already returns. You would have to either pass a callback intogetSize()
or havegetSize()
return a promise.function getSize(itemSize) { return new Promise(function(resolve) { chrome.storage.local.get('sizePref', function(items) { // Get size preferences from storage resolve(items.sizePref[itemSize]); }); } getSize("whatever").then(function(result) { // code that uses the result here });
这篇关于如何使用函数参数作为变量的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!