我只是想知道如何访问同一哈希中另一个键的值。 从哈希内部。不是通过执行 myHash.key2 = myHash.key1....; 我的意思是一种做法:
var myHash = {
key1: 5,
key2: key1 * 7,
key3: true,
key4: (key3)? "yes" : "no"
};
PS:这只是实际代码的简化版本,实际上每个按键内部都有一些复杂的操作。这些值而不是简单的数字或 bool 值。
最佳答案
您不能在文字定义中引用对象上的其他键。用于根据对象内的其他键或其他值设置键的选项有:
对键使用 getter 函数,该函数可以根据其他属性返回值。
对键使用常规函数,该函数可以根据其他属性返回值。
在文字定义之外分配一个键/值,您可以在其中根据其他键/属性分配静态值。
以下是每个选项的示例:
// use getters for properties that can base their values on other properties
var myHash = {
key1: 5,
get key2() { return this.key1 * 7; },
key3: true,
get key4() { return this.key3 ? "yes" : "no";}
};
console.log(myHash.key2); // 35
// use regular functions for properties that can base
// their values on other properties
var myHash = {
key1: 5,
key2: function() { return this.key1 * 7; },
key3: true,
key4: function() { return this.key3 ? "yes" : "no";}
};
console.log(myHash.key2()); // 35
// assign static properties outside the literal definition
// that can base their values on other properties
var myHash = {
key1: 5,
key3: true
};
myHash.key2 = myHash.key1 * 7;
myHash.key4 = myHash.key3 ? "yes" : "no";
console.log(myHash.key2); // 35
注意:前两个选项是“实时”。如果更改 myHash.key1
的值,则 myHash.key2
或 myHash.key2()
的值也会更改。第三个选项是静态的,myHash.key2
的值不会跟随 myHash.key1
中的更改。
关于javascript - 在javascript中分配另一个键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535140/