如何通过键从chrome.storage.local获取值?键值访问语法问题求助
Hey there! The issue you're hitting is a common one with JavaScript object property access — let's break it down and fix your code.
The Core Problem
In JavaScript, when you use the dot notation (like items.tile), you're referencing a property name as a literal string. But when you want to use a variable (like str or Keys[i]) to access a property, you need to use bracket notation instead.
Let's Fix Your Code Snippets
Let's go through each problematic line one by one:
Replacing
items.strwithitems[str]
Yourstrvariable holds the string"tile", so instead of trying to access a property namedstr(which doesn't exist), use brackets to pass the variable's actual value:console.log(items[str]); // This will correctly log the value of items.tileFixing the while loop with
items[Keys[i]]
Similarly,Keys[i]is a variable that holds your target property name, so bracket notation is required here too. I also fixed a small typo (your array was namedvaluebut you were pushing tovalues):var values = []; // Fixed variable name to match the push target chrome.storage.local.get(null, function(items) { var Keys = Object.keys(items); console.log(Keys); let i = Keys.length; // Use let for proper block scoping instead of global i console.log(items.tile); // Works because "tile" is a literal property name var str = String(Keys[6]); console.log(str); // Outputs "tile" console.log(items[str]); // Now works correctly! while (i--) { values.push(items[Keys[i]]); // Bracket notation for dynamic variable keys console.log(values); } })
Why This Works
- Dot notation (
obj.property) only works when you know the exact property name ahead of time (it has to be a valid identifier with no spaces or special characters). - Bracket notation (
obj[variable]) lets you compute the property name dynamically using variables, strings, or even expressions — perfect for cases like looping through object keys.
That should get your code working as expected!
内容的提问来源于stack exchange,提问作者Weee

