如何将未知数量的值作为键值对中的键传递? (Javascript)
How to pass an unknown number of values as a key in key value pairs? (Javascript)
抱歉,标题令人困惑。基本上,我有一个 object 堆 key-value-pairs。例如:
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 中尝试它时,它似乎确实起作用了。这只是每个人都指出的关于逗号运算符如何只取最后一个值的错觉。我现在明白了,将只使用一个普通的多维数组来达到同样的效果。感谢您的帮助。
您可以使用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 '));
抱歉,标题令人困惑。基本上,我有一个 object 堆 key-value-pairs。例如:
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 中尝试它时,它似乎确实起作用了。这只是每个人都指出的关于逗号运算符如何只取最后一个值的错觉。我现在明白了,将只使用一个普通的多维数组来达到同样的效果。感谢您的帮助。
您可以使用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 '));