javascript - 如何引用和计算 Javascript 对象的其他部分?
问题描述
我正在尝试从该对象的 l、w、h 属性中计算基本体积,该对象cube
是item
.
var item = new Object();
item["cube"] = {
dimensions: [1.00,2.00,1.50, "in"], // l, w, h, unit (inches)
volume: (this.dimensions[0] * this.dimensions[1] * this.dimensions[2]) // V = l * w * h
};
alert( item["cube"].volume + item["cube"].dimensions[3] ); // Volume + unit (inches)
我也尝试this
在计算体积时不使用,而是指定对象的确切部分:item["cube"][dimensions][0] * item["cube"][dimensions][1] * item["cube"][dimensions][2]
.
目标是获得警报3.00in
或3in
. 关于我做错了什么以及这是否可行的任何建议?我可以将函数放入对象中吗?
编辑:添加实际功能:
var item = new Object();
function calcVolume (l,w,h) {
return l * w * h;
};
item["cube"] = {
dimensions: [1.00,2.00,1.50, "in"], // l, w, h, unit (inches)
volume: calcVolume(this.dimensions[0],this.dimensions[1],this.dimensions[2]) // V = l * w * h
};
alert( item["cube"].volume + item["cube"].dimensions[3] ); // Volume + unit (inches)
解决方案
您可以getter
为此使用 a 。
var item = new Object();
function calcVolume (l,w,h) { return l * w * h;};
item["cube"] = {
dimensions: [1.00,2.00,1.50, "in"], // l, w, h, unit (inches)
get volume() { return calcVolume(this.dimensions[0],this.dimensions[1],this.dimensions[2]) }
};
alert( item["cube"].volume + item["cube"].dimensions[3] ); // Volume + unit (inches)
虽然我认为这将是ES6 类的一个很好的例子:
class Cube {
constructor(l, w, h, unit) {
this.l = l;
this.w = w;
this.h = h;
this.unit = unit || "in";
}
get volume() { return this.l * this.w * this.h };
get volumeAsString() { return this.volume + this.unit };
}
var c = new Cube(1.00, 2.00, 1.50);
console.log(c.volumeAsString);
推荐阅读
- amazon-web-services - Lambda - 获取函数开始时间并计算单个函数的并发运行函数
- neural-network - 我们如何结合 ANN+CNN 和结合 CNN+SVM?
- node.js - Cloud SQL 可以同步导出吗?或者如果是异步的,如何捕获并重试失败?
- ios - 我将如何显示多个视频、图像?当我上传多张图片和视频时
- java - Python(服务器)从Java(客户端)接收数据在单独的行中..(TCP)
- hexagon-dsp - 在 Hexagon DSP 上进行分析
- appium-ios - 由于不受信任的企业开发人员问题,无法启动应用程序
- ios - 无法为网络层推断通用参数“T”
- dart - 显示一个简单的小吃店
- python - 有没有办法让石墨烯与 django GenericRelation 字段一起工作?