使用Javascript:变量数组的键 [英] Javascript: variable as array key

查看:119
本文介绍了使用Javascript:变量数组的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即时通讯建设和数组,其中我的数组关键是这样一个变量:

I im building and array where my array key is from a variable like this:

var art = $('#article_id').val();
var stk =  $('#stk').val();
elements ={ art : stk };
alert(elements[art]);

但我结束了此输出艺术=> 50 而不是 5123 => 50

推荐答案

您不能创建对象字面那样。你需要写

You cannot create object literals like that. You need to write

elements = {};
elements[art] = stk;

之所以元素= {艺术:STK} 不工作是因为它等同于元素= {艺术:STK} (带引号)。这两个版本在JavaScript中是等价的,只要艺术是一个合法的标识符,而第二个版本可以清楚发生了什么事情。

The reason why elements = { art: stk } does not work is because it is equivalent to elements = { "art": stk } (with quotes). The two versions are equivalent in JavaScript as long as art is a legal identifier, and the second version makes it clear what's going on.

这篇关于使用Javascript:变量数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆