gpt4 book ai didi

javascript - 我在访问对象的属性时得到的值与我期望的值不同

转载 作者:行者123 更新时间:2023-11-29 22:09:35 24 4
gpt4 key购买 nike

我无法访问对象的属性。

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

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

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".

});

})

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

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

最佳答案

问题是您将字符串用作数组,而字符串使用方括号语法来访问字符。这基本上就是您正在做的,但不会起作用:

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

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

字符串 literal 不是 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'] 的数组。

关于javascript - 我在访问对象的属性时得到的值与我期望的值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18798019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com