// 일반적인 즉시 함수 
(function (a) {
    console.log(100);
    // 100
})(100);

// 1. 즉시 실행 
!function (a) {
    console.log(a);
    // 100
}(100);

//
true && function (a) {
    console.log(a);
    // 100
}(100);

1 ? function (a) {
    console.log(a);
    // 100
}(100) : 0;

0, function (a) {
    console.log(a);
    // 100
}(100);

var b = function (a) {
    console.log(a);
    // 100
}(100);

function f2() { }
f2(function (a) {
    console.log(a);
    // 100
}(100))

var f3 = function c(a) {
    console.log(a);
    // 100
}(100);

new function(){
    console.log(100);
    // 100
};

블로그 이미지

미나미나미

,

1-1. 테스트

for(let j = 0; j < 10; j++){
    var arr = [];
    console.time("1-1.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        arr[i] = i;
    }

    console.timeEnd('1-1.calculatingTime');

    //  -------------------------------------
    var arr = [];
    console.time("2-1.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        arr.push(i);
    }
    console.timeEnd('2-1.calculatingTime');
}

   1-2. 결과 :

        익스의 경우 arr[i] = i가 성능상 빠름,

        크롬의 경우 arr[i]가 빠르다고 생각하여 테스트를 진행하였으나,

        엎치락뒤치락 하는 기록이 있음 (평균값. arr[i] = i : 20.79489746ms , arr.push(i) : 24.61420898)

     


 2-1. 테스트 

var j = 0;
for (j = 0; j < 10; j++) {
    var sum = 0;
    var arr = [];
    console.time("1.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        sum += i;
        arr[i] = sum;
    }

    console.timeEnd('1.calculatingTime');
}
//  -------------------------------------
var j = 0;
for (j = 0; j < 10; j++) {
    var sum = 0;
    var arr = [];
    console.time("2.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        sum += i;
        arr.push(sum);
    }

    console.timeEnd('2.calculatingTime');
}

2-2 결과 

        익스의 경우 여전히 arr[i] = i가 성능상 빠름,

        크롬의 경우 엎치락뒤치락 하는 기록이 있음 (평균값. arr[i] = i : 75.38521ms , arr.push(i) : 78.85928)


 

블로그 이미지

미나미나미

,

_.partial 함수

 : 함수의 인자를 일부분 지정 후, 함수 호출 시 인자를 추가적으로 지정하는 함수.

 

 

예제. 인자값을 모두 더하는 함수

// 인자값을 모두 더하는 함수 
function add(){
    var result = 0;
    for(var i =0; i < arguments.length; i++){
		// 인자값 확인
		console.log('arg['+i+']' + ' =>' + arguments[i]); 
        result +=arguments[i];
    }
    return result;
}

// add 함수의 첫번째 인자를 비워두고, 2번째 인자에는 3으로 채운다
var addTest = _.partial(add, _ , 3);

console.log("result = > " + addTest(2)); 
// arg[0] =>2
// arg[1] =>3
// result = > 5

// 최종적으로 인자값이 2, 3, 10, 100 
console.log("result = > " + addTest(2 , 10 , 100)); 
VM1073:6 arg[0] =>2
VM1073:6 arg[1] =>3
VM1073:6 arg[2] =>10
VM1073:6 arg[3] =>100
VM1252:1 result = > 115


예제. 

var student = {
    studnetName : "abc", 
    studentNumber : "20201000",
    studentPrint : _.partial(function(a, b){
        return a + this.studentNumber  + ", " + b + this.studnetName;
    } , "학번 : " , "이름 :")
};
console.log("student = > " + student.studentPrint());

var callStu = student.studentPrint.call({studnetName : "kukkuku" , studentNumber : "20191000"});
console.log("callStu = > " + callStu);

// 새로운 함수를 return
var bindStu = student.studentPrint.bind({studnetName : "zerotototo" , studentNumber : "201999999"});
console.log("bindStu = > " + bindStu());
// VM2322:8 student = > 학번 : 20201000, 이름 :abc
// VM2322:10 callStu = > 학번 : 20191000, 이름 :kukkuku
// VM2322:12 bindStu = > 학번 : 201999999, 이름 :zerotototo

블로그 이미지

미나미나미

,

# Json 값을 받아서 화면에 표현해야 하는 경우.

    - JSON 값을 div에 보여줘야하는 경우, JsonView.js을 통해서 보여주려고 한다.

   

# 결과화면 밑에 전체코드가 있습니다.

 


1. head에 선언한 Script : Jquery , jsonview.js , jsonview.css 

 <!-- Jquery -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>

    <link rel="stylesheet" href="Module/JsonView/jquery.jsonview.css">
    <script src="Module/JsonView/jquery.jsonview.js"></script>

    <!-- CDN 연결 방식 -->
    <!-- <link rel="stylesheet" href="https://rawgithub.com/yesmeck/jquery-jsonview/master/dist/jquery.jsonview.css" /> -->
    <!-- <script type="text/javascript"src="https://rawgithub.com/yesmeck/jquery-jsonview/master/dist/jquery.jsonview.js"></script> -->

2. body 부분. 

    - textarea 값에 테스트를 위해서 좀 길게 넣었습니다.

 <p>textArea에 json 값을 넣어주세요</p>
    <textarea id="jsonValue" rows="10" cols="100">
         [
  {
    "_id": "5dac8d111cd0990d5d52b96a",
    "index": 0,
    "guid": "f9cf4cfd-8a42-4a1d-9fc4-81049c3080aa",
    "isActive": true,
    "balance": "$1,780.36",
    "address": "229 Kermit Place, Nipinnawasee, District Of Columbia, 1696",
    "about": "Est mollit eiusmod dolor aliqua labore deserunt excepteur occaecat minim. Cupidatat est aliqua sint duis do. In voluptate aliquip eiusmod velit.\r\n",
    "registered": "2014-05-15T03:59:40 -09:00",
    "latitude": 37.243509,
    "longitude": -171.874641,
    "tags": [
      "mollit",
      "exercitation",
      "nisi",
      "consequat",
      "non",
      "adipisicing",
      "ullamco"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Vega Wallace"
      },
      {
        "id": 1,
        "name": "Ingrid Neal"
      },
      {
        "id": 2,
        "name": "Janie Soto"
      }
    ],
    "greeting": "Hello, undefined! You have 6 unread messages.",
    "favoriteFruit": "strawberry"
  },
  {
    "_id": "5dac8d11b430a10d199a3697",
    "index": 1,
    "guid": "6b02729a-8328-429e-b965-a8553eff4d09",
    "isActive": true,
    "balance": "$3,770.58",
    "address": "234 Lewis Avenue, Shasta, Kansas, 1815",
    "about": "Laboris ipsum incididunt sunt Lorem. Lorem officia nostrud laboris quis consequat ullamco elit magna irure. Consectetur duis cupidatat est in quis velit quis mollit.\r\n",
    "registered": "2016-05-15T04:52:17 -09:00",
    "latitude": 12.9566,
    "longitude": 61.266088,
    "tags": [
      "cillum",
      "sint",
      "consequat",
      "veniam",
      "quis",
      "nisi",
      "eu"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Shaw Haney"
      },
      {
        "id": 1,
        "name": "Lavonne Pace"
      },
      {
        "id": 2,
        "name": "Kemp Ingram"
      }
    ],
    "greeting": "Hello, undefined! You have 6 unread messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "5dac8d113641fe4d5b543d7d",
    "index": 2,
    "guid": "48d1dddf-70e0-4a92-8ae4-ec6662a0584d",
    "isActive": true,
    "balance": "$2,200.18",
    "address": "744 Crosby Avenue, Kersey, Virginia, 5923",
    "about": "Nostrud ad reprehenderit voluptate dolore irure cupidatat qui nulla id ullamco non mollit veniam ullamco. Sit qui ad tempor tempor commodo ea sunt sunt duis commodo. Proident laborum velit nostrud proident mollit esse laboris sit cillum eu consequat veniam ad consectetur. Voluptate amet excepteur non sit. Veniam nisi est duis officia et irure.\r\n",
    "registered": "2014-11-29T05:10:48 -09:00",
    "latitude": -10.512397,
    "longitude": 156.17502,
    "tags": [
      "laboris",
      "aliquip",
      "labore",
      "aliquip",
      "occaecat",
      "qui",
      "Lorem"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Harding Reilly"
      },
      {
        "id": 1,
        "name": "Pierce Pena"
      },
      {
        "id": 2,
        "name": "Leonard Padilla"
      }
    ],
    "greeting": "Hello, undefined! You have 8 unread messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "5dac8d118842409a7b4a592a",
    "index": 3,
    "guid": "8454e85a-4404-432e-80f3-dd7539e1c0ef",
    "isActive": false,
    "balance": "$2,683.27",
    "address": "466 Navy Walk, Brewster, Texas, 6693",
    "about": "Veniam officia aute aliqua reprehenderit deserunt ut cupidatat anim aliqua esse incididunt nulla sunt exercitation. Culpa non voluptate nostrud in. Dolore laboris enim cillum ut proident aliqua aliquip dolore magna veniam fugiat enim. Officia eiusmod do culpa fugiat ut eiusmod consequat enim duis. Anim consequat est aliquip id laborum nisi minim do occaecat. Elit irure amet ipsum nulla ut reprehenderit quis labore ut. Elit eiusmod sunt dolore mollit consectetur velit dolor.\r\n",
    "registered": "2016-03-07T08:32:31 -09:00",
    "latitude": 1.005155,
    "longitude": 67.81042,
    "tags": [
      "veniam",
      "duis",
      "in",
      "ex",
      "laboris",
      "amet",
      "mollit"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Bradshaw Castaneda"
      },
      {
        "id": 1,
        "name": "Nellie Merrill"
      },
      {
        "id": 2,
        "name": "Sandoval Hickman"
      }
    ],
    "greeting": "Hello, undefined! You have 4 unread messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "5dac8d116840f5652fec481f",
    "index": 4,
    "guid": "567f7cef-bbf3-431a-bc96-06250cfd39ad",
    "isActive": true,
    "balance": "$1,726.97",
    "address": "490 Durland Place, Aurora, Massachusetts, 7419",
    "about": "Sint magna fugiat laborum consequat enim enim qui in nostrud incididunt eiusmod aliqua adipisicing pariatur. Tempor reprehenderit incididunt incididunt eiusmod ut elit mollit excepteur et culpa commodo. Culpa laborum et veniam est culpa voluptate. Dolore aliqua in nisi mollit commodo aliquip nisi aliquip velit aute mollit. Sit et est ut mollit aute adipisicing. Deserunt eu eu pariatur eiusmod commodo adipisicing culpa exercitation ut. Enim esse eiusmod fugiat reprehenderit adipisicing adipisicing culpa minim magna reprehenderit.\r\n",
    "registered": "2018-10-21T05:49:28 -09:00",
    "latitude": -58.404005,
    "longitude": -95.751783,
    "tags": [
      "ullamco",
      "nulla",
      "id",
      "reprehenderit",
      "quis",
      "consectetur",
      "sit"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Allison Burnett"
      },
      {
        "id": 1,
        "name": "David Sharp"
      },
      {
        "id": 2,
        "name": "Hattie Osborn"
      }
    ],
    "greeting": "Hello, undefined! You have 4 unread messages.",
    "favoriteFruit": "strawberry"
  },
  {
    "_id": "5dac8d11eca02cdd7090c991",
    "index": 5,
    "guid": "60ab4eb0-991a-425c-ad3c-919329a13142",
    "isActive": true,
    "balance": "$1,204.71",
    "address": "330 Stewart Street, Harviell, Wyoming, 9337",
    "about": "Est irure ex aute amet adipisicing incididunt exercitation incididunt laborum reprehenderit. Aliquip aliquip tempor deserunt magna qui nostrud velit ea eu voluptate laborum. Occaecat reprehenderit dolore consectetur eiusmod. Do ea adipisicing velit eiusmod quis laborum commodo nostrud. Dolore eiusmod occaecat elit ad proident elit velit nisi fugiat labore excepteur officia.\r\n",
    "registered": "2014-11-09T02:33:56 -09:00",
    "latitude": -2.544352,
    "longitude": 152.762735,
    "tags": [
      "tempor",
      "culpa",
      "adipisicing",
      "amet",
      "aliquip",
      "ad",
      "commodo"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Middleton Lewis"
      },
      {
        "id": 1,
        "name": "Aguilar Lindsey"
      },
      {
        "id": 2,
        "name": "Douglas Finch"
      }
    ],
    "greeting": "Hello, undefined! You have 5 unread messages.",
    "favoriteFruit": "apple"
  }
]  </textarea>

    <!-- JSON을 담을 div -->
    <div id="json" style="width: 500px; height: 500px; border: 1px solid;"></div>

    <div>
        <!-- textarea에 쓰여진 string 값을 읽어서 json으로 표현 -->
        <button id="transJson">Json 값 표현하기</button>
        <!-- 표현된 json 값 뭉치기 -->
        <button id="collapse-btn">Json 합치기</button>
        <!-- json 값 펼치기  -->
        <button id="expand-btn">Json 펼치기</button>
        <!-- Toggle -->
        <button id="toggle-btn">Toggle</button>
        <!-- 깊이 1  -->
        <button id="toggle-level1-btn">Toggle 깊이 1</button>
        <!-- 깊이 2  -->
        <button id="toggle-level2-btn">Toggle 깊이 2</button>
        <!-- 깊이 3  -->
        <button id="toggle-level3-btn">Toggle 깊이 3</button>
    </div>

 

 


3. Script 부분.

<script>
        $(function () {
            // 값 뭉치기
            $('#collapse-btn').on('click', function () {
                $('#json').JSONView('collapse');
            });
            // 값 펼치기
            $('#expand-btn').on('click', function () {
                $('#json').JSONView('expand');
            });
            // toggle
            $('#toggle-btn').on('click', function () {
                $('#json').JSONView('toggle');
            });
            // 깊이 1
            $('#toggle-level1-btn').on('click', function () {
                $('#json').JSONView('toggle', 1);
            });
            // 깊이 2
            $('#toggle-level2-btn').on('click', function () {
                $('#json').JSONView('toggle', 2);
            });
            // 깊이 3
            $('#toggle-level3-btn').on('click', function () {
                $('#json').JSONView('toggle', 3);
            });
            // string json 값을 Json으로 변환.
            $("#transJson").on("click", function () {
                let jsonValue = $("#jsonValue").val().trim();
                // String의 값 json을 변환.
                jsonValue = JSON.parse(jsonValue);
                $('#json').JSONView(jsonValue);
            });
        });
    </script>

4. 결과화면.


#전체코드

...더보기

<!DOCTYPE html>

<html>

 

<head>

    <meta charset="utf-8">

    <title>JS Bin</title>

 

    <!-- Jquery -->

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"

        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"

        crossorigin="anonymous"></script>

 

    <link rel="stylesheet" href="Module/JsonView/jquery.jsonview.css">

    <script src="Module/JsonView/jquery.jsonview.js"></script>

 

    <!-- CDN 연결 방식 -->

    

    

</head>

 

<body>

    <p>textArea에 json 값을 넣어주세요</p>

    <textarea id="jsonValue" rows="10" cols="100">

    [

  {

    "_id": "5dac8d111cd0990d5d52b96a",

    "index": 0,

    "guid": "f9cf4cfd-8a42-4a1d-9fc4-81049c3080aa",

    "isActive": true,

    "balance": "$1,780.36",

    "address": "229 Kermit Place, Nipinnawasee, District Of Columbia, 1696",

    "about": "Est mollit eiusmod dolor aliqua labore deserunt excepteur occaecat minim. Cupidatat est aliqua sint duis do. In voluptate aliquip eiusmod velit.\r\n",

    "registered": "2014-05-15T03:59:40 -09:00",

    "latitude": 37.243509,

    "longitude": -171.874641,

    "tags": [

      "mollit",

      "exercitation",

      "nisi",

      "consequat",

      "non",

      "adipisicing",

      "ullamco"

    ],

    "friends": [

      {

        "id": 0,

        "name": "Vega Wallace"

      },

      {

        "id": 1,

        "name": "Ingrid Neal"

      },

      {

        "id": 2,

        "name": "Janie Soto"

      }

    ],

    "greeting": "Hello, undefined! You have 6 unread messages.",

    "favoriteFruit": "strawberry"

  },

  {

    "_id": "5dac8d11b430a10d199a3697",

    "index": 1,

    "guid": "6b02729a-8328-429e-b965-a8553eff4d09",

    "isActive": true,

    "balance": "$3,770.58",

    "address": "234 Lewis Avenue, Shasta, Kansas, 1815",

    "about": "Laboris ipsum incididunt sunt Lorem. Lorem officia nostrud laboris quis consequat ullamco elit magna irure. Consectetur duis cupidatat est in quis velit quis mollit.\r\n",

    "registered": "2016-05-15T04:52:17 -09:00",

    "latitude": 12.9566,

    "longitude": 61.266088,

    "tags": [

      "cillum",

      "sint",

      "consequat",

      "veniam",

      "quis",

      "nisi",

      "eu"

    ],

    "friends": [

      {

        "id": 0,

        "name": "Shaw Haney"

      },

      {

        "id": 1,

        "name": "Lavonne Pace"

      },

      {

        "id": 2,

        "name": "Kemp Ingram"

      }

    ],

    "greeting": "Hello, undefined! You have 6 unread messages.",

    "favoriteFruit": "apple"

  },

  {

    "_id": "5dac8d113641fe4d5b543d7d",

    "index": 2,

    "guid": "48d1dddf-70e0-4a92-8ae4-ec6662a0584d",

    "isActive": true,

    "balance": "$2,200.18",

    "address": "744 Crosby Avenue, Kersey, Virginia, 5923",

    "about": "Nostrud ad reprehenderit voluptate dolore irure cupidatat qui nulla id ullamco non mollit veniam ullamco. Sit qui ad tempor tempor commodo ea sunt sunt duis commodo. Proident laborum velit nostrud proident mollit esse laboris sit cillum eu consequat veniam ad consectetur. Voluptate amet excepteur non sit. Veniam nisi est duis officia et irure.\r\n",

    "registered": "2014-11-29T05:10:48 -09:00",

    "latitude": -10.512397,

    "longitude": 156.17502,

    "tags": [

      "laboris",

      "aliquip",

      "labore",

      "aliquip",

      "occaecat",

      "qui",

      "Lorem"

    ],

    "friends": [

      {

        "id": 0,

        "name": "Harding Reilly"

      },

      {

        "id": 1,

        "name": "Pierce Pena"

      },

      {

        "id": 2,

        "name": "Leonard Padilla"

      }

    ],

    "greeting": "Hello, undefined! You have 8 unread messages.",

    "favoriteFruit": "apple"

  },

  {

    "_id": "5dac8d118842409a7b4a592a",

    "index": 3,

    "guid": "8454e85a-4404-432e-80f3-dd7539e1c0ef",

    "isActive": false,

    "balance": "$2,683.27",

    "address": "466 Navy Walk, Brewster, Texas, 6693",

    "about": "Veniam officia aute aliqua reprehenderit deserunt ut cupidatat anim aliqua esse incididunt nulla sunt exercitation. Culpa non voluptate nostrud in. Dolore laboris enim cillum ut proident aliqua aliquip dolore magna veniam fugiat enim. Officia eiusmod do culpa fugiat ut eiusmod consequat enim duis. Anim consequat est aliquip id laborum nisi minim do occaecat. Elit irure amet ipsum nulla ut reprehenderit quis labore ut. Elit eiusmod sunt dolore mollit consectetur velit dolor.\r\n",

    "registered": "2016-03-07T08:32:31 -09:00",

    "latitude": 1.005155,

    "longitude": 67.81042,

    "tags": [

      "veniam",

      "duis",

      "in",

      "ex",

      "laboris",

      "amet",

      "mollit"

    ],

    "friends": [

      {

        "id": 0,

        "name": "Bradshaw Castaneda"

      },

      {

        "id": 1,

        "name": "Nellie Merrill"

      },

      {

        "id": 2,

        "name": "Sandoval Hickman"

      }

    ],

    "greeting": "Hello, undefined! You have 4 unread messages.",

    "favoriteFruit": "apple"

  },

  {

    "_id": "5dac8d116840f5652fec481f",

    "index": 4,

    "guid": "567f7cef-bbf3-431a-bc96-06250cfd39ad",

    "isActive": true,

    "balance": "$1,726.97",

    "address": "490 Durland Place, Aurora, Massachusetts, 7419",

    "about": "Sint magna fugiat laborum consequat enim enim qui in nostrud incididunt eiusmod aliqua adipisicing pariatur. Tempor reprehenderit incididunt incididunt eiusmod ut elit mollit excepteur et culpa commodo. Culpa laborum et veniam est culpa voluptate. Dolore aliqua in nisi mollit commodo aliquip nisi aliquip velit aute mollit. Sit et est ut mollit aute adipisicing. Deserunt eu eu pariatur eiusmod commodo adipisicing culpa exercitation ut. Enim esse eiusmod fugiat reprehenderit adipisicing adipisicing culpa minim magna reprehenderit.\r\n",

    "registered": "2018-10-21T05:49:28 -09:00",

    "latitude": -58.404005,

    "longitude": -95.751783,

    "tags": [

      "ullamco",

      "nulla",

      "id",

      "reprehenderit",

      "quis",

      "consectetur",

      "sit"

    ],

    "friends": [

      {

        "id": 0,

        "name": "Allison Burnett"

      },

      {

        "id": 1,

        "name": "David Sharp"

      },

      {

        "id": 2,

        "name": "Hattie Osborn"

      }

    ],

    "greeting": "Hello, undefined! You have 4 unread messages.",

    "favoriteFruit": "strawberry"

  },

  {

    "_id": "5dac8d11eca02cdd7090c991",

    "index": 5,

    "guid": "60ab4eb0-991a-425c-ad3c-919329a13142",

    "isActive": true,

    "balance": "$1,204.71",

    "address": "330 Stewart Street, Harviell, Wyoming, 9337",

    "about": "Est irure ex aute amet adipisicing incididunt exercitation incididunt laborum reprehenderit. Aliquip aliquip tempor deserunt magna qui nostrud velit ea eu voluptate laborum. Occaecat reprehenderit dolore consectetur eiusmod. Do ea adipisicing velit eiusmod quis laborum commodo nostrud. Dolore eiusmod occaecat elit ad proident elit velit nisi fugiat labore excepteur officia.\r\n",

    "registered": "2014-11-09T02:33:56 -09:00",

    "latitude": -2.544352,

    "longitude": 152.762735,

    "tags": [

      "tempor",

      "culpa",

      "adipisicing",

      "amet",

      "aliquip",

      "ad",

      "commodo"

    ],

    "friends": [

      {

        "id": 0,

        "name": "Middleton Lewis"

      },

      {

        "id": 1,

        "name": "Aguilar Lindsey"

      },

      {

        "id": 2,

        "name": "Douglas Finch"

      }

    ],

    "greeting": "Hello, undefined! You have 5 unread messages.",

    "favoriteFruit": "apple"

  }

]

    </textarea>

 

    <!-- JSON을 담을 div -->

    <div id="json" style="width: 500px; height: 500px; border: 1px solid; overflow: auto;"></div>

 

    <div>

        <!-- textarea에 쓰여진 string 값을 읽어서 json으로 표현 -->

        <button id="transJson">Json 값 표현하기</button>

        <!-- 표현된 json 값 뭉치기 -->

        <button id="collapse-btn">Json 합치기</button>

        <!-- json 값 펼치기  -->

        <button id="expand-btn">Json 펼치기</button>

        <!-- Toggle -->

        <button id="toggle-btn">Toggle</button>

        <!-- 깊이 1  -->

        <button id="toggle-level1-btn">Toggle 깊이 1</button>

        <!-- 깊이 2  -->

        <button id="toggle-level2-btn">Toggle 깊이 2</button>

        <!-- 깊이 3  -->

        <button id="toggle-level3-btn">Toggle 깊이 3</button>

    </div>

 

    <script>

        $(function () {

            // 값 뭉치기

            $('#collapse-btn').on('click'function () {

                $('#json').JSONView('collapse');

            });

            // 값 펼치기

            $('#expand-btn').on('click'function () {

                $('#json').JSONView('expand');

            });

            // toggle

            $('#toggle-btn').on('click'function () {

                $('#json').JSONView('toggle');

            });

            // 깊이 1

            $('#toggle-level1-btn').on('click'function () {

                $('#json').JSONView('toggle'1);

            });

            // 깊이 2

            $('#toggle-level2-btn').on('click'function () {

                $('#json').JSONView('toggle'2);

            });

            // 깊이 3

            $('#toggle-level3-btn').on('click'function () {

                $('#json').JSONView('toggle'3);

            });

            // string json 값을 Json으로 변환.

            $("#transJson").on("click"function () {

                let jsonValue = $("#jsonValue").val().trim();

                // String의 값 json을 변환.

                jsonValue = JSON.parse(jsonValue);

                $('#json').JSONView(jsonValue);

            });

        });

    </script>

</body>

 

</html>

블로그 이미지

미나미나미

,

가장 아래의 결과화면이 있습니다. 

 

head 에서 jquery 파일을 불러옵니다.

cdn으로 불러오실 경우 3번째 줄을 사용하세요.

<script src="js/jquery-1.12.3.js"></script>
<!-- 또는 -->
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>

- body 부분

 <div id=wrap>
    <div>
      <!-- 버튼을 실행시 이전, 다음으로 움직이다 -->
      <button class="prev"> 이전</button>
      <button class="next"> 다음</button>
    </div>
    <!-- 움직일 이미지들 -->
    <div class=imgBox style="width:500px;height:500px;">
      <!-- free url 사진 -->
      <img class="img on" src="https://images.unsplash.com/photo-1556034910-07855ebf6606?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="">
      <img class="img" src="https://images.unsplash.com/photo-1556241298-fce5ee86ea48?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="">
      <img class="img" src="https://images.unsplash.com/photo-1556032743-3a694170ef94?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" alt="">
    </div>
  </div>

 

- CSS 부분

 

 .img {
      position: absolute;
      width:500px;
      height:500px;
      -webkit-transition: opacity 1s ease-in-out;
      -moz-transition: opacity 1s ease-in-out;
      -o-transition: opacity 1s ease-in-out;
      transition: opacity 1s ease-in-out;
      opacity: 0;
      -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
      filter: alpha(opacity=0);
    }

    .img:first-child {
      /* display: block; */
      opacity: 1;
    }

    #wrap {
      padding: 20px;
    }

    div {
      margin: 5px 0px
    }

 

 

- JavaScript 부분

$(".prev").on("click", function (e) {
      e.preventDefault();

      // 이미지 현재의 위치
      var imgOn = $(".imgBox").find(".on").index();
      // 이미지 총 개수 
      var imgLen = $(".imgBox .img").length;
      console.log(imgOn)
      
      // imgBox안의 img 중 imgOn 번째의 on 클래스 삭제 
      $(".imgBox .img").eq(imgOn).removeClass("on");
      // imgBox안의 img 중 imgOn 번째 숨기기 
      $(".imgBox .img").eq(imgOn).css("opacity", 0);
      
      //  이전의 위치로 돌아가야함으로
      imgOn = imgOn -1;

      if( imgOn < 0 ){
        // 돌아가 위치가 -1일 경우 
        // 이미지의 마지막으로 돌아간다
        $(".imgBox .img").eq(imgLen -1).css("opacity", 1);
        $(".imgBox .img").eq(imgLen -1).addClass("on");
      }else{
        // 돌아갈 위치가 -1이 아닌 경우
        $(".imgBox .img").eq(imgOn).css("opacity", 1);
        $(".imgBox .img").eq(imgOn).addClass("on");
      }

    });

    $(".next").on("click", function (e) {
      e.preventDefault();
      // 위에 동일 
      var imgOn = $(".imgBox").find(".on").index();
      var imgLen = $(".imgBox .img").length;

      // 위에 동일
      $(".imgBox .img").eq(imgOn).removeClass("on");
      $(".imgBox .img").eq(imgOn).css("opacity", 0);
      
      // 다음의 위치로 알아야 되기 때문에 
      imgOn = imgOn + 1;
      
      if( imgOn === imgLen ){
        // 다음의 위치가 총 개수보다 클 경우
        // 처음의 위치로 돌아간다
        $(".imgBox .img").eq(0).css("opacity", 1);
        $(".imgBox .img").eq(0).addClass("on");
      }else{
        // 다음 위치가 있는 경우 
        $(".imgBox .img").eq(imgOn).css("opacity", 1);
        $(".imgBox .img").eq(imgOn).addClass("on");
      }
    });

 

- 결과 화면.

See the Pen img slider by Nami (@NamuNami) on CodePen.

 

 

블로그 이미지

미나미나미

,

 

자바스크립트로 input의 자동완성을 구현해보도록 하겠습니다.

# https://www.w3schools.com/howto/howto_js_autocomplete.asp 를 참고하였습니다.

 


- head 부분 

따로, Jquery를 사용하지않고, 자바스크립트만으로 구현을 하였습니다.

<head>
    <title>자동생성파일</title>
    <!-- css에는 autocomplet의 요소를 만들떄 필요한 css가 담겨져 있습니다. -->
    <link rel="stylesheet" href="css/autocomplete.css">
    <!-- css에는 autocomplet의 요소를 만들떄 필요한 scrpit가 담겨져 있습니다. -->
    <script type="text/javascript" src="js/autocomplate.js"></script>
    <!-- css에는 autocomplet의 요소의 샘플 json의 값이 담겨져 있습니다. -->
    <script type="text/javascript" src="js/animal.js"></script>
</head>

- body 부분

<body onload="init()">
    <!-- 아래의 input의 값을 받을 때, 자동완성 기능이 작동합니다. -->
    <div class="srch_form autocomplete">
        <input id="autoInput" placeholder="Search...">
    </div>
    <script>
        // autocomplete 부분을 생성
        window.onload = function () {
            autocomplete.setAutocomplete(document.getElementById("autoInput"), animal)
        }
    </script>
</body>

- 화면 설명

input에 특정한 값을 입력하면, 그 값에 따라서 자동완성 기능을 수행합니다.

 


 

- css (autocomplete.css) : autocomplete 기능에 필요한 css

.autocomplete {
    position: relative;
    display: inline-block;
}

.autocomplete-items {
    position: absolute;
    border: 1px solid #d4d4d4;
    border-bottom: none;
    border-top: none;
    z-index: 99;
     top: 100%;
    left: 0;
    right: 0;
}

.autocomplete-items div {
    padding: 10px;
    cursor: pointer;
    background-color: #fff;
    border-bottom: 1px solid #d4d4d4;
}

.autocomplete-items div:hover {
    background-color: #e9e9e9;
}

.autocomplete-active {
   background-color: DodgerBlue !important;
    color: #ffffff;
}

 


 

- animal.js : autocomplete를 테스트할 json 값.

var animal = ["Aardvark","Albatross","Alligator","Alpaca","Ant","Anteater","Antelope","Ape","Armadillo","Donkey","Baboon","Badger","Barracuda","Bat","Bear","Beaver","Bee","Bison","Boar","Buffalo","Butterfly","Camel","Capybara","Caribou","Cassowary","Cat","Caterpillar","Cattle","Chamois","Cheetah","Chicken","Chimpanzee","Chinchilla","Chough","Clam","Cobra","Cockroach","Cod","Cormorant","Coyote","Crab","Crane","Crocodile","Crow","Curlew","Deer","Dinosaur","Dog","Dogfish","Dolphin","Dotterel","Dove","Dragonfly","Duck","Dugong","Dunlin","Eagle","Echidna","Eel","Eland","Elephant","Elk","Emu","Falcon","Ferret","Finch","Fish","Flamingo","Fly","Fox","Frog","Gaur","Gazelle","Gerbil","Giraffe","Gnat","Gnu","Goat","Goldfinch","Goldfish","Goose","Gorilla","Goshawk","Grasshopper","Grouse","Guanaco","Gull","Hamster","Hare","Hawk","Hedgehog","Heron","Herring","Hippopotamus","Hornet","Horse","Human","Hummingbird","Hyena","Ibex","Ibis","Jackal","Jaguar","Jay","Jellyfish","Kangaroo","Kingfisher","Koala","Kookabura","Kouprey","Kudu","Lapwing","Lark","Lemur","Leopard","Lion","Llama","Lobster","Locust","Loris","Louse","Lyrebird","Magpie","Mallard","Manatee","Mandrill","Mantis","Marten","Meerkat","Mink","Mole","Mongoose","Monkey","Moose","Mosquito","Mouse","Mule","Narwhal","Newt","Nightingale","Octopus","Okapi","Opossum","Oryx","Ostrich","Otter","Owl","Oyster","Panther","Parrot","Partridge","Peafowl","Pelican","Penguin","Pheasant","Pig","Pigeon","Pony","Porcupine","Porpoise","Quail","Quelea","Quetzal","Rabbit","Raccoon","Rail","Ram","Rat","Raven","Red deer","Red panda","Reindeer","Rhinoceros","Rook","Salamander","Salmon","Sand Dollar","Sandpiper","Sardine","Scorpion","Seahorse","Seal","Shark","Sheep","Shrew","Skunk","Snail","Snake","Sparrow","Spider","Spoonbill","Squid","Squirrel","Starling","Stingray","Stinkbug","Stork","Swallow","Swan","Tapir","Tarsier","Termite","Tiger","Toad","Trout","Turkey","Turtle","Viper","Vulture","Wallaby","Walrus","Wasp","Weasel","Whale","Wildcat","Wolf","Wolverine","Wombat","Woodcock","Woodpecker","Worm","Wren","Yak","Zebra"
]

 

 


- autocomplate.js : autocomplete를 수행하는 스크립트

 

싱글톤으로 작성되었으며 , 아래의 주석은 쭈욱 따라가시면서 파악하시면 좋을 것 같습니다.

let autocomplete = (function () {

    let _inp = null;

    let _arr = [];

    let _currentFocus;

    let _setAutocomplete = function (inp, arr) {
        // autocomplete할 배열
        _arr = arr;

        // 기존의 input 값과 같지 않다면, 리스너 해제
        if (_inp === inp) {
            return;
        }
        // 기존 리스너해제
        _removeListener();

        // 새로운 input 의 리스너 추가.
        _inp = inp;
        _inp.addEventListener("input", inputEvent);
        _inp.addEventListener("keydown", keydownEvent);
    }

    let inputEvent = function (e) {
        var a, b, i, val = this.value;

        // 이전 생성된 div 제거 
        closeAllLists();

        // 요소 확인
        if (!val) {
            return false;
        }

        // 현재의 포커스의 위치는 없음.
        _currentFocus = -1;

        // autocomplet에서 항목을 보여줄 div 생성
        a = document.createElement("DIV");
        // 
        a.setAttribute("id", this.id + "autocomplete-list");
        // css 적용 
        a.setAttribute("class", "autocomplete-items");

        // input 아래의 div 붙이기.
        this.parentNode.appendChild(a);

        // autocomplet할 요소 찾기
        for (i = 0; i < _arr.length; i++) {
            // 배열의 요소를 현재 input의 value의 값만큼 자른 후, 같으면 추가한다.
            if (_arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
                b = document.createElement("DIV");
                // value의 값 만큼 굵게 표시 
                b.innerHTML = "<strong>" + _arr[i].substr(0, val.length) + "</strong>";
                b.innerHTML += _arr[i].substr(val.length);
                b.innerHTML += "<input type='hidden' value='" + _arr[i] + "'>";

                // console.log(b); 
                // <div class="autocomplete-active"><strong>B</strong>adger<input type="hidden" value="Badger"></div>

                // 생성된 div에서 이벤트 발생시 hidden으로 생성된 input안의 value의 값을 autocomplete할 요소에 넣기
                b.addEventListener("click", function (e) {
                    _inp.value = this.getElementsByTagName("input")[0].value;
                    closeAllLists();
                });

                // autocomplete 리스트를 붙이기.
                a.appendChild(b);
            }
        }
    }

    let keydownEvent = function (e) {
        // 
        var x = document.getElementById(this.id + "autocomplete-list");
        // 선택할 요소 없으면 null ,
        // <div id="autoInputautocomplete-list" class="autocomplete-items"><div class="autocomplete-active"><strong>A</strong>ardvark<input type="hidden" value="Aardvark"></div><div><strong>A</strong>lbatross<input type="hidden" value="Albatross"></div><div><strong>A</strong>lligator<input type="hidden" value="Alligator"></div><div><strong>A</strong>lpaca<input type="hidden" value="Alpaca"></div><div><strong>A</strong>nt<input type="hidden" value="Ant"></div><div><strong>A</strong>nteater<input type="hidden" value="Anteater"></div><div><strong>A</strong>ntelope<input type="hidden" value="Antelope"></div><div><strong>A</strong>pe<input type="hidden" value="Ape"></div><div><strong>A</strong>rmadillo<input type="hidden" value="Armadillo"></div></div>
        if (x) {
            // 태그 네임을 가지는 엘리먼트의 유요한 html 컬렉션을 반환.
            // div의 값을 htmlCollection의 값으로 받아옴.
            x = x.getElementsByTagName("div");
        }

        if (e.keyCode == 40) {
            // down
            // 현재위치 증가
            _currentFocus++;
            // 현재위치의 포커스 나타내기
            addActive(x);
        } else if (e.keyCode == 38) {
            // up
            // 현재위치 감소
            _currentFocus--;
            // 현재위치의 포커스 나타내기
            addActive(x);
        } else if (e.keyCode == 13) {
            // enter
            e.preventDefault();
            // 현재위치가 아이템 선택창내에 있는 경우
            if (_currentFocus > -1) {
                // 현재 위치의 값 클릭
                if (x) x[_currentFocus].click();
            }
        }
    }

    // document.addEventListener("click", function (e) {
    //     closeAllLists(e.target);
    // });


    let addActive = function (x) {
        if (!x) return false;
        removeActive(x);
        if (_currentFocus >= x.length) _currentFocus = 0;
        if (_currentFocus < 0) _currentFocus = (x.length - 1);
        x[_currentFocus].classList.add("autocomplete-active");
    }


    let removeActive = function (x) {
        for (var i = 0; i < x.length; i++) {
            x[i].classList.remove("autocomplete-active");
        }
    }


    let closeAllLists = function (elmnt) {
        var x = document.getElementsByClassName("autocomplete-items");
        for (var i = 0; i < x.length; i++) {
            if (elmnt != x[i] && elmnt != _inp) {
                x[i].parentNode.removeChild(x[i]);
            }
        }
    }


    let _removeListener = function () {
        if (_inp !== null) {
            console.log(_inp)
            _inp.removeEventListener("input", inputEvent, false);
            _inp.removeEventListener("keydown", keydownEvent, false);
        }
    }
    return {

        setAutocomplete: function (inp, arr) {
            _setAutocomplete(inp, arr);
        },
    }

})();

 

 


- 폴더 구조 : 위에 소스를 아래와 같은 폴더 구조로 만들어서 사용하시면 동일하게 작동할겁니다.

- 결과 화면

블로그 이미지

미나미나미

,

[javascript] 특정문자 길이로 자르기 (match함수) 



match함수를 통한

특정문자 길이로 자르는 경우로 자르기.




1. 아래의 코드를 사용한다.


function chunkString(str, length) {
//length의 길이 만큼 글자를 자른다.
return str.match(new RegExp('.{1,' + length + '}', 'g'));
// 정규식으로 length의 길이만 큼 자라서 배열로 return 합니다.
}




2. 결과화면 





블로그 이미지

미나미나미

,

[javascript] 자바스크립트 화면 캡쳐하기 (html2canvas.js) 


화면을 캡쳐하기 위해서 

javascript를 통하여 캡쳐하도록 해보겠습니다.


html2canvas.js 사용해보기



1. html2canvas.js 코드를 가져옵니다.


공식홈페이지 : https://html2canvas.hertzen.com/ 

또는 githumb 주소 : https://github.com/niklasvh/html2canvas/releases



 



2. script를 설정해줍니다. (jquery가 필요없습니다 . 생략이 가능합니다.)


<script src="js/html2canvas.js"></script>

 



3. body를 표현합니다. (screenshot을 테스트 환경을 위해서)


<!-- 전체 부분-->
<button onclick=bodyShot()>bodyShot</button>
<!-- 일부분 부분-->
<button onclick=partShot()>partShot</button>

<div class="container" id='container'>
<!-- 로컬에서 불러온 파일 -->
<img src="img/1534347627.jpg">
<!-- 웹에서 불러온 파일 -->
<img src="https://www.w3schools.com/html/img_girl.jpg">
<!-- <img src="https://source.unsplash.com/user/erondu/400x400"> -->
</div>
<!-- 결과화면을 그려줄 canvas -->
<canvas id="canvas" width="900" height="600"
style="border:1px solid #d3d3d3;"></canvas>





4. 버튼 2개에 대해서 이벤트를 만들어줍니다.


function bodyShot() {
//전체 스크린 샷하기
html2canvas(document.body)
//document에서 body 부분을 스크린샷을 함.
.then(
function (canvas) {
//canvas 결과값을 drawImg 함수를 통해서
//결과를 canvas 넘어줌.
//png의 결과 값
drawImg(canvas.toDataURL('image/png'));

//appendchild 부분을 주석을 풀게 되면 body
//document.body.appendChild(canvas);

//특별부록 파일 저장하기 위한 부분.
saveAs(canvas.toDataURL(), 'file-name.png');
}).catch(function (err) {
console.log(err);
});
}

function partShot() {
//특정부분 스크린샷
html2canvas(document.getElementById("container"))
//id container 부분만 스크린샷
.then(function (canvas) {
//jpg 결과값
drawImg(canvas.toDataURL('image/jpeg'));
//이미지 저장
saveAs(canvas.toDataURL(), 'file-name.jpg');
}).catch(function (err) {
console.log(err);
});
}

function drawImg(imgData) {
console.log(imgData);
//imgData의 결과값을 console 로그롤 보실 수 있습니다.
return new Promise(function reslove() {
//내가 결과 값을 그릴 canvas 부분 설정
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//canvas의 뿌려진 부분 초기화
ctx.clearRect(0, 0, canvas.width, canvas.height);

var imageObj = new Image();
imageObj.onload = function () {
ctx.drawImage(imageObj, 10, 10);
//canvas img를 그리겠다.
};
imageObj.src = imgData;
//그릴 image데이터를 넣어준다.

}, function reject() { });

}
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
window.open(uri);
}
}






5. 결과화면




로컬의 이미지들은 캡쳐가 되나 그 외는 캡쳐가 되지를 않는다....


이 부분을 해결하고 싶지만 아직은 해결 하지 못했다.





블로그 이미지

미나미나미

,