在javascript中分配另一个键的值 [英] Assigning the value of another key in javascript
问题描述
我只想知道如何在同一个哈希中访问另一个键的值。哈希内部的
。不是通过做myHash.key2 = myHash.key1 ....;
我的意思是一种做法:
I would just like to know how to access the value of another key in the same hash. from inside the hash. not by doing myHash.key2 = myHash.key1....; I mean a way of doing :
var myHash = {
key1: 5,
key2: key1 * 7,
key3: true,
key4: (key3)? "yes" : "no"
};
PS:这只是实际代码的简化版本,实际上每个密钥都有一些复杂的操作。值而不是简单的数字或bools。
PS: this is only a simplified version of the actual code in fact every key has some complex operations inside. The values and not simple Numbers or bools.
推荐答案
您不能在文字定义中引用对象上的其他键。根据对象中的其他键或其他值设置键的选项包括:
You cannot refer to other keys on the object within a literal definition. The options for setting a key based on other keys or other values within the object are:
-
使用键的getter函数可以根据其他属性返回值。
Use a getter function for the key that can return a value based on other properties.
使用常规函数作为可以根据其他属性返回值的键。
Use a regular function for the key that can return a value based on other properties.
在文字定义之外指定一个键/值,您可以根据其他键/属性分配静态值。
Assign a key/value outside of the literal definition where you can assign a static value based on the other keys/properties.
以下是每个选项的示例:
Here are examples of each of these options:
// 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()
也会改变。第三个选项是static, myHash.key2
的值不会跟随 myHash.key1
中的更改。
Note: the first two options are "live". If you change the value of myHash.key1
, then the value of myHash.key2
or myHash.key2()
will change too. The third option is static and the values of myHash.key2
will not follow changes in myHash.key1
.
这篇关于在javascript中分配另一个键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!