You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过键从chrome.storage.local获取值?键值访问语法问题求助

Fixing Object Property Access with Variable Keys

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:

  1. Replacing items.str with items[str]
    Your str variable holds the string "tile", so instead of trying to access a property named str (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.tile
    
  2. Fixing 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 named value but you were pushing to values):

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:27:47