developer tip

자바 스크립트의 "변수"변수?

copycodes 2020. 9. 3. 20:03
반응형

자바 스크립트의 "변수"변수?


PHP에서 "변수"변수를 가질 수 있다는 것을 알고 있습니다. 예를 들면

$x = "variable";
$$x = "hello, world!";
echo $variable; // displays "hello, world!"

javascript에서 이름으로 변수를 문자열로 참조 할 수 있습니까? 어떻게 될까요?


이에 대한 단일 솔루션은 없습니다 (글쎄요 eval,하지만 심각하게 고려하지 않겠습니다). 를 통해 일부 전역 변수에 동적으로 액세스 할 수 window있지만 함수에 로컬 인 변수에는 작동하지 않습니다. 속성 이되지 않는 전역 변수는 , 및 es로 window정의 된 변수 입니다.letconstclass

변수 변수를 사용하는 것보다 거의 항상 더 나은 솔루션이 있습니다! 대신 데이터 구조를 살펴보고 문제에 맞는 구조 를 선택 해야합니다 .

다음과 같이 고정 된 이름 집합이있는 경우

// BAD
var foo = 42;
var bar = 21;

var key = 'foo';
console.log(eval(key));

이러한 이름 / 값을 객체의 속성으로 저장하고 대괄호 표기법사용 하여 동적으로 조회합니다.

// GOOD
var obj = {
  foo: 42,
  bar: 21,
};

var key = 'foo';
console.log(obj[key]);

ES2015 + 에서는 간결한 속성 표기법을 사용하여 기존 변수에 대해이 작업을 수행하는 것이 훨씬 더 쉽습니다 .

// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};

var key = 'foo';
console.log(obj[key]);


다음과 같이 "연속적으로"번호가 매겨진 변수가있는 경우

// BAD
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';

var index = 1;
console.log(eval('foo' + index));

그런 다음 대신 배열 을 사용하고 인덱스를 사용하여 해당 값에 액세스해야합니다.

// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);


이 작업을 필사적으로 수행하려면 eval ()을 사용해 볼 수 있습니다.

var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);

또는 창 개체 사용 :

var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);

http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript


문자열만으로 자바 스크립트에서 변수를 참조하려면 다음을 사용할 수 있습니다.

window['your_variable_name']

변수 및 변수의 개체도 설정하고 참조 할 수 있습니다.


var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);

Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a gloabls array for you. For example, instead of declaring the variable hello in the global scope like this:

var hello = 'hello world';

let's encapsulate it inside an object. We'll call that object vv (variable variables):

var vv = {
    'hello': 'hello world',
    //Other variable variables come here.
},
referToHello = 'hello';

Now we can refer to the variable by it's index, and since array indexes can be provided using a variable we are de facto making use of a variable variable:

console.log(vv[referToHello]); //Output: hello world

The Answer To Your Question

Let's apply this to the code you supplied in the original question:

    var vv = {
        'x': 'variable',
        'variable': 'hello world!'
    };
    console.log(vv[vv['x']]); //Displays "hello, world!"

A Practical Use

While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.

var elementIds = [],
        elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
        elements.forEach( (element) => {
            elementIds[element] = document.getElementById(element);
        });

This example declares variable variables (keys in elementIds) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside the elementIds array) is not only neat, but also more responsible.


Of course you can, but don't. The variables have to be global.

var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])

You can use the JavaScript eval(str) function.

What this function does is convert the string provided into JS code, then executes it.

For example:

eval("console.log('hello world')"); // Logs hello world

So to use it as a variable variable, you can do the following:

var a = "hello";
var hello = "world";
console.log(a + " " + eval(a)); // Logs hello world

This will produce the exact same output as:

console.log(a + " " + hello); // Logs hello world

(Example is taken from the PHP manual on variable variables.)

참고URL : https://stackoverflow.com/questions/5187530/variable-variables-in-javascript

반응형