简体   繁体   English

Javascript我如何通过引用传递一个int

[英]Javascript how can i pass an int by reference

Is it possible to pass an int by reference in Javascript? 是否可以通过JavaScript引用传递int?

function myFunction(myval) {
    myval = 3 
}

a = Number(5)
myFunction(a)
console.log(a) //gives 5

How can I get 3, instead of 5? 如何获得3个而不是5个?

I found a solution myself like this 我自己找到了解决办法

function myFunction(myval) {
    myval.val = 3
}

a = { val: 5 }
myFunction(a)
console.log(a.val)

see frederik's comment below which clears my confusion about Number. 请参阅下面的frederik评论,这消除了我对Number的困惑。

Why it gives undefined 为什么给出undefined

Because there is no explicit return from myFunction so it implicitly returns undefined which is being printed in console 因为没有从myFunction显式返回,所以它隐式返回undefined ,这将在控制台中打印

 function myFunction(myval) { myval = 3 } a = 5 console.log(myFunction(a)) 


In a non-constructor context (ie, without the new operator), Number can be used to perform a type conversion. 在非构造函数上下文中(即,没有new运算符),Number可用于执行类型转换。

 let a = Number(5) console.log(typeof a) 


You can do something like this 你可以做这样的事情

 function myFunction(myval) { myval.a = 3 } let obj = { a : 5 } myFunction(obj) console.log(obj) 

You cannot pass a number by reference. 您不能通过引用传递数字。 Here example with object: 这里的对象示例:

 function incrementTheCounter(obj) { obj.counter++; } const a = {counter: 5}; incrementTheCounter(a); console.log(a.counter); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM