gpt4 book ai didi

Javascript 数组 - 使用变量作为键

转载 作者:行者123 更新时间:2023-12-02 18:09:54 24 4
gpt4 key购买 nike

我正在尝试检索一个数组值,其中键是一个变量。 JSFiddle here -- 在行业输入中输入“服装”或“书籍”。 JSFiddle 的输出表明返回的值未定义。

问题在于var filename = Constants.factsheet - 如何正确传递factsheet的值来检索关联的文件名?

JS:

  $(function () {

var availableIndustries = ["apparel", "books"];

$("#industry").autocomplete({
source: availableIndustries
});

$("input[type=image]")
.button()
.click(function (event) {

var constants = {
'apparel': 'apparel.pdf',
'books': 'publishing.pdf',
};

var factsheet = document.getElementById('industry').value;
var filename = constants.factsheet;
$('#factsheet').text('Your factsheet is ' + factsheet);
$('#file').text('Your filename is ' + filename);

});
});

最佳答案

更改:

var filename = constants.factsheet;

至:

var filename = constants[factsheet];

(请注意,您的常量不是数组。它是一个对象。)

在 JavaScript 中,您可以通过两种方式访问​​对象属性:使用点表示法和文字属性名称 (constants.apparel),或使用括号表示法和字符串属性名称 (constants [“服装”])。在第二种情况下,字符串可以是任何表达式的结果,包括变量查找。所以这些都显示了同样的事情:

// Dot notation
console.log(constants.apparel);

// Brackets with string literal
console.log(constants["apparel"]);

// Brackets with concatentation expression
console.log(constants["app" + "arel"]);

// Brackets using a variable
var name = "apparel";
console.log(constants[name]);

// Brackets using the return value of a function
function foo() { return "apparel"; }
console.log(constants[foo()]);

你明白了。

关于Javascript 数组 - 使用变量作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794133/

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