LoginSignup
2
4

More than 5 years have passed since last update.

変数名を変数にする方法 - Javascript

Last updated at Posted at 2018-02-10

結論


var associativeArray = {};
var collect_variable = "変数の名前"
associativeArray[""+collect_variable] = "valuae";

/*
*
*
*
*/
console.log( associativeArray[""+collect_variable] ); 

検証

paiza.ioで実行

process.stdin.resume();
process.stdin.setEncoding('utf8');

var associativeArray = {}; //オブジェクトを用意
var collect_variable = "変数名です" //変数名にしたい変数を""の中に定義
var dummy_variable = "ダミー" //変数名が変数であることを証明するためのダミー(意味はない)

associativeArray[""+collect_variable] = "valuae"; //作った変数(ここでは[変数名です]という文字列が変数名になる)を変数名として、変数にvaluaeという値を代入

console.log("変数の値を出力");
console.log( associativeArray[""+collect_variable] ); //変数の値を出力、valueと出力される
//console.log( associativeArray["変数名です"] ); でも同じ結果が得られる

console.log("変数名が変数であることの証明");
console.log( associativeArray[""+dummy_variable] ); //ダミーなんて変数名はないので、undefinedと出力される

swiftで書き換えると

Swiftだったらディクショナリーを使って、こう書きます


//: Playground - noun: a place where people can play

import UIKit

var dictionary: Dictionary<String, Any> = [:]
let collect_variable = "変数名です" //変数名にしたい変数を""の中に定義
let dummy_variable = "ダミー"
dictionary[collect_variable] = "valuae"; //作った変数(ここでは[変数名です]という文字列が変数名になる)を変数名として、変数にvaluaeという値を代入

print(dictionary[collect_variable]!) //変数の値を出力、valueと出力される
//print(dictionary["変数名です"]!) でも同じ結果が得られる

print(dictionary[dummy_variable]!) //ダミーなんて変数名はないので、ここでエラーになる
//Fatal error: Unexpectedly found nil while unwrapping an Optional value

参考

How to do associative array/hashing in JavaScript
【JavaScript】連想配列のkeyとvalueの取得

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4