반응형

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

var d = new Date();
var n = d.getDay();

getDay() 메서드는 지정된 날짜의 요일(0~6)을 반환합니다.

참고: 일요일은 0, 월요일은 1 등입니다.

var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

 

https://www.w3schools.com/js/js_date_methods.asp

 

JavaScript Get Date Methods

Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

 

 

반응형
반응형

고정 길이의 문자열이 되도록 숫자 앞에 0을 추가하는 방법이 있습니까? 

예를 들어 2자리를 지정하면 5는 "05"가 됩니다.

 

 

Small one-liner function using the ES2017 String.prototype.padStart method:

const zeroPad = (num, places) => String(num).padStart(places, '0')

console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"

Another ES5 approach:


function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)

 

https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript

 

How to output numbers with leading zeros in JavaScript?

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

stackoverflow.com

 

반응형
반응형

EJS - Embedded JavaScript templating.

<%= EJS %>

https://ejs.co/

 

EJS -- Embedded JavaScript templates

Simple syntax JavaScript code in simple, straightforward scriptlet tags. Just write JavaScript that emits the HTML you want, and get the job done!

ejs.co

Options

  • cache Compiled functions are cached, requires filename
  • filename Used by cache to key caches, and for includes
  • root Set project root for includes with an absolute path (e.g, /file.ejs). Can be array to try to resolve include from multiple directories.
  • views An array of paths to use when resolving includes with relative paths.
  • context Function execution context
  • compileDebug When false no debug instrumentation is compiled
  • client Returns standalone compiled function
  • delimiter Character to use for inner delimiter, by default '%'
  • openDelimiter Character to use for opening delimiter, by default '<'
  • closeDelimiter Character to use for closing delimiter, by default '>'
  • debug Outputs generated function body
  • strict When set to `true`, generated function is in strict mode
  • _with Whether or not to use with() {} constructs. If false then the locals will be stored in the locals object. (Implies `--strict`)
  • localsName Name to use for the object storing local variables when not using with Defaults to locals
  • rmWhitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace. It also enables a safer version of -%> line slurping for all scriptlet tags (it does not strip new lines of tags in the middle of a line).
  • escape The escaping function used with <%= construct. It is used in rendering and is .toString()ed in the generation of client functions. (By default escapes XML).
  • outputFunctionName Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags.
  • async When true, EJS will use an async function for rendering. (Depends on async/await support in the JS runtime.Tags
    • <% 'Scriptlet' tag, for control-flow, no output
    • <%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
    • <%= Outputs the value into the template (HTML escaped)
    • <%- Outputs the unescaped value into the template
    • <%# Comment tag, no execution, no output
    • <%% Outputs a literal '<%'
    • %> Plain ending tag
    • -%> Trim-mode ('newline slurp') tag, trims following newline
    • _%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it

 

 

.

반응형
반응형

[Node.js]  Path : 파일 경로를 다루고 변경하는 유틸리티가 포함되어 있다

https://nodejs.sideeffect.kr/docs/v0.10.0/api/path.html

 

Path Node.js v0.10.0 Manual & Documentation

Path# Stability: 3 - Stable This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid. Use require('path') to use

nodejs.sideeffect.kr

path.normalize(p)#

'..'와 '.' 부분을 처리해서 문자열 경로를 정규화한다.

슬래시가 여러 개 있는 경우 슬래시 하나로 교체하고 경로의 마지막에 슬래시가 있는 경우에는 유지한다. windows에서는 역슬래시를 사용한다.

path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'

path.join([path1], [path2], [...])#

모든 아규먼트를 합쳐서 최종 경로로 정규화한다. 문자열이 아닌 아규먼트는 무시한다.

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns
'/foo/bar/baz/asdf'

path.join('foo', {}, 'bar')
// returns
'foo/bar'

path.resolve([from ...], to)#

to를 절대경로로 변환한다.

to가 절대경로가 아니면 절대경로를 찾을 때까지 from 아규먼트들을 우측에서 좌측의 순서로 앞에 이어붙힌다.모든 from 경로를 사용한 후에도 절대경로를 찾지 못하면 현재 워킹 디렉토리를 사용한다. 최종 경로는 정규화되고 경로가 루트 디렉토리로 처리되지 않는한 마지막 슬래시는 제거한다. 문자열이 아닌 아규먼트는 무시한다.

이는 쉘에서 cd 명령어를 순서대로 실행한 것과 같다.

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')

//-- 이는 다음과 비슷하다.:

cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd

//--다른 경로라 존재할 필요가 없거나 파일일 수도 있다는 점만이 다르다.

path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
'/home/myself/node/wwwroot/static_files/gif/image.gif'

 

path.relative(from, to)#

from에서 to까지의 상대경로를 처리한다.

때로는 두 개의 절대경로를 가지고 있고 하나에서 다른 하나로의 상대경로를 얻어야 한다. 사실 이는 path.resolve의 반대 변환이다. 이 의미를 다음 예제에서 보자.

path.resolve(from, path.relative(from, to)) == path.resolve(to)

//-----------------------------------------------

path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns
'..\\..\\impl\\bbb'

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns
'../../impl/bbb'

path.dirname(p)#

경로의 디렉토리이름을 반환한다. Unix의 dirname 명령어와 비슷하다.

path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'

path.basename(p, [ext])#

경로의 마지막 부분을 반환한다. Unix의 basename 명령어와 비슷하다.

path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'

path.extname(p)#

경로의 마지막 부분의 문자열에서 마지막 '.'에서부터 경로의 확장자를 반환한다. 경로의 마지막 부분에 '.'가 없거나 첫 글자가 '.'이라면 빈 문자열을 반환한다. 

path.extname('index.html')
// returns
'.html'

path.extname('index.')
// returns
'.'

path.extname('index')
// returns
''

path.sep#

플랫폼의 파일 구분자. '\\'나 '/'이다.

'foo/bar/baz'.split(path.sep)
// returns
['foo', 'bar', 'baz']

 

path.delimiter#

플랫폼에 특화된 경로 구분자인 ;나 ':'이다.

 

console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'

process.env.PATH.split(path.delimiter)
// returns
['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

반응형
반응형

Deno - A secure runtime for JavaScript and TypeScript.

 

Node.js의 개발자 Ryan Dahl이 개발한 개선되고 더 안전한 Node.js,

 

Node는 JavaScript를 실행하기 위한 런타임인 것처럼, Deno는 TypeScript를 실행하기 위한 Command-line 런타임

 

Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust.

  1. Secure by default. No file, network, or environment access, unless explicitly enabled.
  2. Supports TypeScript out of the box.
  3. Ships only a single executable file.
  4. Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  5. Has a set of reviewed (audited) standard modules that are guaranteed to work with Deno: deno.land/std

반응형
반응형

 

https://www.w3schools.com/howto/howto_js_slideshow.asp

 

How To Create a Slideshow

How TO - Slideshow Learn how to create a responsive slideshow with CSS and JavaScript. Slideshow / Carousel A slideshow is used to cycle through elements: ❮ ❯ Create A Slideshow Step 1) Add HTML: Example

www.w3schools.com

 

<!-- Slideshow container -->
<div class="slideshow-container">

  <!-- Full-width images with number and caption text -->
  <div class="mySlides fade">
    <div class="numbertext">1 / 3</div>
    <img src="img1.jpg" style="width:100%">
    <div class="text">Caption Text</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">2 / 3</div>
    <img src="img2.jpg" style="width:100%">
    <div class="text">Caption Two</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">3 / 3</div>
    <img src="img3.jpg" style="width:100%">
    <div class="text">Caption Three</div>
  </div>

  <!-- Next and previous buttons -->
  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</a>
</div>
<br>

<!-- The dots/circles -->
<div style="text-align:center">
  <span class="dot" onclick="currentSlide(1)"></span>
  <span class="dot" onclick="currentSlide(2)"></span>
  <span class="dot" onclick="currentSlide(3)"></span>
</div>
* {box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Hide the images by default */
.mySlides {
  display: none;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}
반응형
반응형

https://threejs.org/

 

Three.js – JavaScript 3D Library

 

threejs.org

https://threejsfundamentals.org/

 

Three.js Fundamentals

Learn Three.js

threejsfundamentals.org

This is the first article in a series of articles about three.js. Three.js is a 3D library that tries to make it as easy as possible to get 3D content on a webpage.

Three.js is often confused with WebGL since more often than not, but not always, three.js uses WebGL to draw 3D. WebGL is a very low-level system that only draws points, lines, and triangles. To do anything useful with WebGL generally requires quite a bit of code and that is where three.js comes in. It handles stuff like scenes, lights, shadows, materials, textures, 3d math, all things that you'd have to write yourself if you were to use WebGL directly.

These tutorials assume you already know JavaScript and, for the most part they will use ES6 style. See here for a terse list of things you're expected to already know. Most browsers that support three.js are auto-updated so most users should be able to run this code. If you'd like to make this code run on really old browsers look into a transpiler like Babel. Of course users running really old browsers probably have machines that can't run three.js.

When learning most programming languages the first thing people do is make the computer print "Hello World!". For 3D one of the most common first things to do is to make a 3D cube. So let's start with "Hello Cube!"

Before we get started let's try to give you an idea of the structure of a three.js app. A three.js app requires you to create a bunch of objects and connect them together. Here's a diagram that represents a small three.js app

Things to notice about the diagram above.

  • There is a Renderer. This is arguably the main object of three.js. You pass a Scene and a Camera to a Renderer and it renders (draws) the portion of the 3D scene that is inside the frustum of the camera as a 2D image to a canvas.
  • There is a scenegraph which is a tree like structure, consisting of various objects like a Scene object, multiple Mesh objects, Light objects, Group, Object3D, and Camera objects. A Scene object defines the root of the scenegraph and contains properties like the background color and fog. These objects define a hierarchical parent/child tree like structure and represent where objects appear and how they are oriented. Children are positioned and oriented relative to their parent. For example the wheels on a car might be children of the car so that moving and orienting the car's object automatically moves the wheels. You can read more about this in the article on scenegraphs.
  • Note in the diagram Camera is half in half out of the scenegraph. This is to represent that in three.js, unlike the other objects, a Camera does not have to be in the scenegraph to function. Just like other objects, a Camera, as a child of some other object, will move and orient relative to its parent object. There is an example of putting multiple Camera objects in a scenegraph at the end of the article on scenegraphs.
  • Mesh objects represent drawing a specific Geometry with a specific Material. Both Material objects and Geometry objects can be used by multiple Mesh objects. For example to draw two blue cubes in different locations we could need two Mesh objects to represent the position and orientation of each cube. We would only need one Geometry to hold the vertex data for a cube and we would only need one Material to specify the color blue. Both Mesh objects could reference the same Geometry object and the same Material object.
  • Geometry objects represent the vertex data of some piece of geometry like a sphere, cube, plane, dog, cat, human, tree, building, etc... Three.js provides many kinds of built in geometry primitives. You can also create custom geometry as well as load geometry from files.
  • Material objects represent the surface properties used to draw geometry including things like the color to use and how shiny it is. A Material can also reference one or more Texture objects which can be used, for example, to wrap an image onto the surface of a geometry.
  • Texture objects generally represent images either loaded from image files, generated from a canvas or rendered from another scene.
  • Light objects represent different kinds of lights.
반응형
반응형

[Javascript] 숫자 3자리 단위마다 콤마(comma) 찍기 

stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript

 

How to print a number with commas as thousands separators in JavaScript

I am trying to print an integer in JavaScript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? Here is how I am...

stackoverflow.com

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
 
function comma(num){
    var len, point, str; 
       
    num = num + ""; 
    point = num.length % 3 ;
    len = num.length; 
   
    str = num.substring(0, point); 
    while (point < len) { 
        if (str != "") str += ","; 
        str += num.substring(point, point + 3); 
        point += 3; 
    } 
     
    return str;
 
}

 

 

반응형

+ Recent posts