Copying, passing, and comparing by value 的 疑惑

moliu 2009-10-21 08:00:14
var n = 1;
var m = n;
function add_to_total(total, x)

{

total = total + x;
document.write(total+"</br>");
document.write(x+"</br>")
}



add_to_total(n, m);//输出 2 和 1,
document.write(n+"</br>")//输出 1
document.write(m+"</br>")//输出 1
// 后面讲解中,提到 n=1 m=2 ,可上面的程序证明,却不是这样。请达人讲解,谢谢

附:js权威指南中的讲解
var n = 1; // Variable n holds the value 1

var m = n; // Copy by value: variable m holds a distinct value 1



// Here's a function we'll use to illustrate passing by value

// As we'll see, the function doesn't work the way we'd like it to

function add_to_total(total, x)

{

total = total + x; // This line changes only the internal copy of total

}



// Now call the function, passing the numbers contained in n and m by value.

// The value of n is copied, and that copied value is named total within the

// function. The function adds a copy of m to that copy of n. But adding

// something to a copy of n doesn't affect the original value of n outside

// of the function. So calling this function doesn't accomplish anything.

add_to_total(n, m);



// Now, we'll look at comparison by value.

// In the following line of code, the literal 1 is clearly a distinct numeric

// value encoded in the program. We compare it to the value held in variable

// n. In comparison by value, the bytes of the two numbers are checked to

// see if they are the same.

if (n == 1) m = 2; // n contains the same value as the literal 1; m is now 2
...全文
132 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
moliu 2009-10-29
  • 打赏
  • 举报
回复
if (n == 1) m = 2; // n contains the same value as the literal 1; m is now 2
//n 值确实 为 1 ,给 m 重新赋值 2,m is now 2 。原来 m 值 为 1 。
//原来是这样理解的,以为 m 的值为 2 ,是函数执行后的结果。这样的理解是错误的。
moliu 2009-10-24
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 fandelei1982 的回复:]
if (n == 1) m = 2;  // n contains the same value as the literal 1; m is now 2

[/Quote]
还是不明白。为什么 m=2 ?
moliu 2009-10-21
  • 打赏
  • 举报
回复
var n = 1;
var m = n;
function add_to_total(total, x)

{

total = total + x;
document.write(total+" </br>");
document.write(x+" </br>")
}
add_to_total(n, m);//输出 2 和 1
//这如何解释?
friendly_ 2009-10-21
  • 打赏
  • 举报
回复

if (n == 1) m = 2; // n contains the same value as the literal 1; m is now 2
内容概要:本文介绍了一种基于多目标粒子群算法(MOPSO)的微电网优化调度模型,综合考虑风能、光伏、储能系统、柴油发电机、燃气轮机以及与主电网之间的能量交互等多种分布式能源的协同运行。通过构建以运行成本最小化、碳排放最低化和系统可靠性最优化为目标的多目标优化模型,利用Matlab平台实现MOPSO算法求解,完成对微电网在不同运行场景下的能量管理与调度方案优化。该模型能够有效平衡经济性与环保性之间的关系,适用于含多类型分布式电源的复杂微电网系统,具有较强的工程应用价值和科研参考意义; 适合人群:具备一定电力系统基础知识和Matlab编程能力的研究生、科研人员及工程技术人员,尤其适合从事微电网、智能电网、综合能源系统、可再生能源集成与优化调度等领域研究的专业人士; 使用场景及目标:①用于多能源耦合微电网系统的协同优化调度研究;②支持多目标智能优化算法在能源系统中的建模与求解实践,帮助用户掌握MOPSO在实际工程问题中的应用方法;③为学术论文复现、毕业设计、科研项目开发提供完整的代码实例与技术支撑; 阅读建议:建议读者结合Matlab代码与理论文档,深入理解目标函数构建、约束条件处理及Pareto最优解集生成机制,重点关注算法参数设置、多目标权衡分析与结果可视化,并可通过调整能源配置或引入新约束进行二次开发与创新研究。

87,988

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧