抱歉,标题令人困惑。基本上,我有一个对象,它有一堆键值对。例如:
this[1,2] = "some output";
如果我知道密钥将由两个值组成,我可以这样做:
let someValue = 1;
let someOtherValue = 2;
console.log(this[someValue,someOtherValue]);
//Outputs "some output"
但是,如果我的键是由一些值"n“组成的,而我知道这一点的唯一方法是从其他一些变量:
var numberOfKeys = n;
例如,我如何访问第一个值(0,0,0,0...)用代码?提前感谢,我希望你能理解这个问题。
编辑:谢谢大家,我现在明白了。最初,我认为传入多个值作为键的想法是行不通的,但当我在JSfiddle中尝试它时,它似乎确实行得通。这只是大家所指出的逗号运算符如何取最后一个值所给出的错觉。我现在明白了,我将使用一个普通的多维数组来达到同样的效果。谢谢你的帮助。
发布于 2018-06-13 06:25:08
您可以使用map
来映射您想要访问的键:
// Your object
const object = {
firstKey: 'first value',
secondKey: 'second value',
thirdKey: 'third value',
};
// Your n number of keys
const keys = ['firstKey', 'thirdKey'];
// Map over the keys you want to get and return values
const result = keys.map(key => object[key]);
// Do something with the values
console.log(result.join(' and '));
https://stackoverflow.com/questions/50826610
复制相似问题