我只想知道如何在同一个散列中访问另一个键的值。从哈希里面。不是通过执行myHash.key2 =myHash.key1.;我指的是一种方法:
var myHash = {
key1: 5,
key2: key1 * 7,
key3: true,
key4: (key3)? "yes" : "no"
};PS:这只是实际代码的一个简化版本,实际上每个键都有一些复杂的操作。而不是简单的数字或布尔值。
发布于 2015-11-05 01:32:45
不能在文字定义中引用对象上的其他键。根据对象中的其他键或其他值设置键的选项如下:
以下是每个选项的示例:
// 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中的更改。
发布于 2015-11-05 01:38:35
首先,您需要使用关键字this引用对象属性。取而代之的是这样做:
var myHash = {
key1: 5,
key2: 11,
key3: true,
isKey3true: function(){
var r = this.key3 ? 'yes' : 'no';
return r;
}
}
myHash.key1 = 100;
console.log(key2); // key2 not a method
myHash.key3 = false;
console.log(myHash.isKey3true()); // method will review key3 valuehttps://stackoverflow.com/questions/33535140
复制相似问题