Javascript 에서 참조별로 com/go/4e6b330a_kr 전달하십시오 어떻게 합니까? 나는 내가 바라는 건 3 변수 I want for 루프는 여러 작업을 수행할 수 있기 때문에 배치할 수 있으며 각각의 업무를 수행합니다.
dtep 코드:
myArray = new Array(var1, var2, var3);
for (var x = 0; x < myArray.length; x++){
//do stuff to the array
makePretty(myArray[x]);
}
//now do stuff to the updated vars
What is the best way to do this?
&Quot reference", 지나갈 수 없다. javascript 에서 사용할 수 있습니다. 객체를 전달할 수 있습니다, 즉 객체에 대한 참조가 pass by value 말할 수 있습니다) 한 후 투명지에 함수 객체를 수정할 내용:
function alterObject(obj) {
obj.foo = "goodbye";
}
var myObj = { foo: "hello world" };
alterObject(myObj);
alert(myObj.foo); // "goodbye" instead of "hello world"
속성을 반복할 수 있는 어레이에서는 수정하십시오 숫자 인덱스할 각 셀을 어레이이며 스케쳐내.
var arr = [1, 2, 3];
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] + 1;
}
function swap(a, b) {
var tmp = a;
a = b;
b = tmp; //assign tmp to b
}
var x = 1, y = 2;
swap(x, y);
alert("x is " + x + ", y is " + y); // "x is 1, y is 2"
, & 편집하십시오 mdash; 이 최근 (2015년 3월) 에 다시 날려버린 블로그 포스트를 통해, 이 경우 유사한 레딧 내거냐 표시되어도 대한 아래에 언급된 것으로 나타났습니다. It 수행됨 내게 있는 것이 큰 부분을 읽는 동안 이리저리 레딧 의견 충돌, 단어 관련된 불행한 에서 혼란을 " reference". 용어 " 지나갈 reference"; 및 " 지나갈 value"; 이미 선행 总监和首席信息官完全了解 " objects"; 프로그래밍 언어에서 사용할 수 있는. # 39 의 it& 전혀 객체에 대한 정말 아니에요. # 39 에 대한 함수 매개 변수, 함수, 특히 it& 어떻게 매개변수입니다 " connected"; (방관하겠나) 를 호출하는 환경. 특히 참고로 :에서 진정한 참조별로 전달하십시오 & mdash;; , 은 방정식입니다 & mediaagent 객체에는 mdash; , 내용을 수정할 수 있게 한 객체에는 여전히 예쁜 애썼는데요 JavaScript 에서 않니다 및 it 엿볼 것 같다. 하지만 한 것이라고 할 수 있는 환경, 또한 개체 참조입니다 수정하십시오 호출하십시오 that& # 39 의 t , # 39 의 주요 심아이엔큐 can& JavaScript 에서 할 수 있습니다. 그러나 한 것 자체가 아니라 언어 참조별로 전달하십시오 전달하십시오 참조 참조입니다 참조 .
, & 편집하십시오 mdash; [블로그 포스트를 슬라이드에서는 자문자답을.] (http://whatsthepointy.blogspot.com/2013/11/javascript-does-not-have-pass-by.html) (참고합니다 의견을 게시하는 것을 설명하는 doesn& c++컴파일러는 # 39, t really 참조별로 전달하십시오 있다. 그렇다. 그러나 일반 참조를 생성할 수 없는 어떤 c++컴파일러는 는 변수, 함수 호출 또는 포인터입니다 시점에 인컨텍스트 명시적으로 만들 수 있는 기능을 수행할 수 있음을 간접적으로 호출할 때 인수 유형 서명입니다 있다. 이들은 주요 창조하셨노 JavaScript doesn& # 39, t support).
'object1 = {제안: " car".};; 'array1 = [1.2,3];
'object1.prop = " car";; array1 [0] = 9; '
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
function passVar(obj1, obj2, num) {
obj1.prop = "laptop"; // will CHANGE original
obj2 = { prop: "computer" }; //will NOT affect original
num = num + 1; // will NOT affect original
}
var object1 = {
prop: "car"
};
var object2 = {
prop: "bike"
};
var number1 = 10;
passVar(object1, object2, number1);
console.log(object1); //output: Object {item:"laptop"}
console.log(object2); //output: Object {item:"bike"}
console.log(number1); //ouput: 10
끝 - < 스니핏 >;!
해결하십시오 전달하는 등 가변적입니다 참조별로:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
< br/>;
넵, 실제로 액세스 할 수 없이 글로벌
inc = (function () {
var variableName = 0;
var init = function () {
variableName += 1;
alert(variableName);
}
return init;
})();
inc();
var ref = { value: 1 };
function Foo(x) {
x.value++;
}
Foo(ref);
Foo(ref);
alert(ref.value); // Alert: 3
function rvar (name, value, context) {
if (this instanceof rvar) {
this.value = value;
Object.defineProperty(this, 'name', { value: name });
Object.defineProperty(this, 'hasValue', { get: function () { return this.value !== undefined; } });
if ((value !== undefined) && (value !== null))
this.constructor = value.constructor;
this.toString = function () { return this.value + ''; };
} else {
if (!rvar.refs)
rvar.refs = {};
if (!context)
context = window;
// Private
rvar.refs[name] = new rvar(name, value);
// Public
Object.defineProperty(context, name, {
get: function () { return rvar.refs[name]; },
set: function (v) { rvar.refs[name].value = v; },
configurable: true
});
return context[name];
}
}
rvar('test_ref');
test_ref = 5; // test_ref.value = 5
또는:
rvar('test_ref', 5); // test_ref.value = 5
rvar('test_ref_number');
test_ref_number = 5;
function Fn1 (v) { v.value = 100; }
console.log("rvar('test_ref_number');");
console.log("test_ref_number = 5;");
console.log("function Fn1 (v) { v.value = 100; }");
console.log('test_ref_number.value === 5', test_ref_number.value === 5);
console.log(" ");
Fn1(test_ref_number);
console.log("Fn1(test_ref_number);");
console.log('test_ref_number.value === 100', test_ref_number.value === 100);
console.log(" ");
test_ref_number++;
console.log("test_ref_number++;");
console.log('test_ref_number.value === 101', test_ref_number.value === 101);
console.log(" ");
test_ref_number = test_ref_number - 10;
console.log("test_ref_number = test_ref_number - 10;");
console.log('test_ref_number.value === 91', test_ref_number.value === 91);
console.log(" ");
console.log("---------");
console.log(" ");
rvar('test_ref_str', 'a');
console.log("rvar('test_ref_str', 'a');");
console.log('test_ref_str.value === "a"', test_ref_str.value === 'a');
console.log(" ");
test_ref_str += 'bc';
console.log("test_ref_str += 'bc';");
console.log('test_ref_str.value === "abc"', test_ref_str.value === 'abc');
rvar('test_ref_number');
test_ref_number = 5;
function Fn1 (v) { v.value = 100; }
test_ref_number.value === 5 true
Fn1(test_ref_number);
test_ref_number.value === 100 true
test_ref_number++;
test_ref_number.value === 101 true
test_ref_number = test_ref_number - 10;
test_ref_number.value === 91 true
---------
rvar('test_ref_str', 'a');
test_ref_str.value === "a" true
test_ref_str += 'bc';
test_ref_str.value === "abc" true
그러나 다른 외곽진입 통과할 수 있는 모든 (로컬, 원시적인) 에 의해 현재 폐쇄 " com/go/4e6b330a_kr 참조별로 랩할 가변으로 fly"; '평가' 에서. 또한, 활용, 수행됨 " strict". (참고: 점을 유념하십시오 '평가' 가 부적합한 JS 옵티 마이저 변수 이름 역시 작은 따옴표로 누각되었습니다 운프레딕트리베 결과를 초래할 수 있다)
"use strict"
//return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}
//demo
//assign argument by reference
function modifyArgument(argRef, multiplier){
argRef.value = argRef.value * multiplier;
}
(function(){
var x = 10;
alert("x before: " + x);
modifyArgument(eval(byRef("x")), 42);
alert("x after: " + x);
})()
라이브 샘플링합니다
function Wrapper(val){
this.VAL = val;
}
Wrapper.prototype.toString = function(){
return this.VAL.toString();
}
function DECLARE(val, callback){
var valWrapped = new Wrapper(val);
callback(valWrapped);
}
function INC(ref){
if(ref && ref.hasOwnProperty('VAL')){
ref.VAL++;
}
else{
ref++;//or maybe throw here instead?
}
return ref;
}
DECLARE(5, function(five){ //consider this line the same as 'let five = 5'
console.log("five is now " + five);
INC(five); // increment
console.log("five is incremented to " + five);
});
function updateArray(context, targetName, callback) {
context[targetName] = context[targetName].map(callback);
}
var myArray = ['a', 'b', 'c'];
updateArray(this, 'myArray', item => {return '_' + item});
console.log(myArray); //(3) ["_a", "_b", "_c"]
개인적으로 싫어하는 " 지나갈 reference"; 기능을 제공하는 다양한 프로그래밍 언어로. 나는 그냥 함수형 프로그래밍 개념 때문에 아마도 that& # 39 의 검색 기능을 갖춘 부작용이 생길 수 있지만, 저는 항상 구스범스 보더라도 같은 조작 통과된 매개변수입니다 참조). 개인적으로 강하게 " 기술 사용, 단일 responsibility". 때문이다.
이럴 경우 단 한 결과 / 사용하여 값을 반품해야 함수는 복귀하십시오 키워드. 아니, 차라리 그냥 대신 매개변수입니다 인수 / 수정 / 인수를 원하는 대로 반품해야 수정날짜 매개변수입니다 가치와 남겨두십시오 reassignment) - 최대 호출하십시오 코드입니다.
하지만 가끔 (그러길 바래야지 매우 드물게) 에서 두 개 이상의 결과 값을 반환되기를 동일한 기능을 합니다. 이 경우, 그 결과 값을 꼭 이래야겠어요 opt 모두 포함할 수 있는 단일 구조 또는 객체. 모든 reassignment) - 다시 호출하는 코드를 최대 처리 해야 합니다.
예:
예를 들어, & # 39 에서 지원하는 등 특별한 키워드를 사용하여 반군지역 매개변수입니다 약간만이라도 ref& # 39;; 이 인수 목록. 내 코드를 볼 수 있다며 이 같은 일이.
//The Function
function doSomething(ref value) {
value = "Bar";
}
//The Calling Code
var value = "Foo";
doSomething(value);
console.log(value); //Bar
대신 난 뭔가 실제로 다음과 같은 것을 선호한다.
//The Function
function doSomething(value) {
value = "Bar";
return value;
}
//The Calling Code:
var value = "Foo";
value = doSomething(value); //Reassignment
console.log(value); //Bar
꼭 이래야겠어요 여러 값을 반환하는 함수를 작성할 필요가 있을 때, 나는 사용하지 않겠다고 매개변수입니다 참조별로 통과 중 하나. 그래서 이 같은 코드를 피할 수 있을 것 "이라고 말했다.
//The Function
function doSomething(ref value) {
value = "Bar";
//Do other work
var otherValue = "Something else";
return otherValue;
}
//The Calling Code
var value = "Foo";
var otherValue = doSomething(value);
console.log(value); //Bar
console.log(otherValue); //Something else
대신 난 새 값을 모두 실제로 포지셔닝하십시오 반환되기를 객체를 인사이드라면 다음과 같습니다.
//The Function
function doSomething(value) {
value = "Bar";
//Do more work
var otherValue = "Something else";
return {
value: value,
otherValue: otherValue
};
}
//The Calling Code:
var value = "Foo";
var result = doSomething(value);
value = result.value; //Reassignment
console.log(value); //Bar
console.log(result.otherValue);
이러한 코드 예제 상당하다는 것을 어떻게 처리할 것이라고 하지만 개인적으로 간편화된 대략 같은 얘기입니다. 날 수 있도록 다양한 책임사용자 유지할 수 있도록 올바른 파일배치.
즐거운 코딩. )
사실은 정말 쉽고 < /h3> h3> <;;; 문제는 한 것을 알고 있습니다 읽기 전용 zone. 범위지정 다른 프로젝트로 반군지역 클래식 인수만
하지만 이는 동일합니까 args 이 글로벌 / 범위지정 가변으로 더 있다.
function action(){
/* process this.arg, modification allowed */
}
action.arg = [ ["empty-array"],"some string",0x100,"last argument" ];
action();
function action(){
/* process this.arg, modification allowed */
this.arg = ["a","b"];
}
action.setArg = function(){this.arg = arguments; return this;}
action.setArg(["empty-array"],"some string",0x100,"last argument")()
또는 그 이상 하지 않았다. '악타이온.스타리 ([", empty-array",],,, 일부 string" " 0x100 ", 마지막 argument") 스칼 ()'
그러니까말이야 정확히요 너희는너희가 짓궂군요. 스위프트는 괜찮서라 될 것 같은 것이 있다 요컨대 '사용' let '아닌' var.
하지만 사실은 프리미티브는 값을 기준으로 전달된 사실을 '나' 의 가치를 var 시점에서 가장 놀라운 것은 이터레이션에 복사되므로 익명 함수 말할 수 없다.
for (let i = 0; i < boxArray.length; i++) {
boxArray[i].onclick = function() { console.log(i) }; // correctly prints the index
}
자바스크립트 항목을 수정하여 어레이입니다 함수 내부에서 (통과되는 어레이당 객체에 대한 참조가 있다).
function makeAllPretty(items) {
for (var x = 0; x < myArray.length; x++){
//do stuff to the array
items[x] = makePretty(items[x]);
}
}
myArray = new Array(var1, var2, var3);
makeAllPretty(myArray);
Here& # 39 의 또 다른 예를 들어:
function inc(items) {
for (let i=0; i < items.length; i++) {
items[i]++;
}
}
let values = [1,2,3];
inc(values);
console.log(values);
// prints [2,3,4]