2

我无法访问对象的属性。

我能够访问对象的属性,但我得到的值与我期望的不同。

这是我现在正在处理的代码。

alertHeading.on('blur', function(){

    var inputtedVal = $(this).val();
    var key = alertMode.val();

    chrome.runtime.getBackgroundPage(function(backgroundPage) {

      var background = backgroundPage.background;

      var alertObject = background.getStorage(key);

      alertObject.heading="aaa";
      alertObject.heading[0]="zero";
      alertObject.heading[1]="one";

      (1)This works fine.
      console.log(alertObject); //outputs Object {heading: "aaa"} 

      (2)These don't work as I expect.
      console.log(alertObject.heading[0]); // outputs a. I'm expecting "zero".
      console.log(alertObject.heading[1]); // outputs a. I'm expecting "one".

    });

  })

我如何能够访问我在写“到”alertObject.heading [0]”的行中设置的值?

请帮我解决这个问题。谢谢!

4

2 回答 2

1

您需要先将 alertObject.heading 实例化为数组,然后分配值。

您正在做的是创建一个“字符串”,然后按索引访问一个字符。

于 2013-09-14T03:43:57.790 回答
1

问题是您将字符串用作数组,并且字符串具有括号语法来访问字符。这基本上是你正在做的,并且不会工作:

var str = 'hello';
str[0] = 'world';

console.log(str, str[0]); //=> hello h

字符串文字不是 JavaScript 中的常规对象。如果您尝试将任何对象用作数组,您仍然可以访问这些属性,但您会将它们存储在该prototype对象的 中。但同样,字符串文字不是常规对象。如果您遵循不好的做法(不要)并使用String构造函数创建一个字符串,您将能够访问不以数字开头的属性:

var str = new String('hello');
str['a'] = 'world'; // or str.a = 'world'

console.log(str, str['a']); //=> hello world

无论如何,你的逻辑没有意义,首先你分配一个字符串然后你想要一个数组?你丢了绳子!尝试这个:

alertObject.heading = ['aaa']; // initialize as array
alertObject.heading[1] = 'zero';
alertObject.heading[2] = 'one';

现在你有一个像['aaa', 'zero', 'one'].

于 2013-09-14T03:45:37.230 回答