반응형
반응형

div처럼 블록 레벨 요소(화면 전체를 차지하는 요소 —옮긴이)를 가지고 있는 태그를 중앙 정렬하기 위해선 margin 속성을 사용하여 값을 0 auto로 주면 됩니다.

 

<div class="container">
  <div class="child"></div>
</div>


.container {
  font-family: arial;
  font-size: 24px;
  margin: 25px;
  width: 350px;
  height: 200px;
  outline: dashed 1px black;
}

.child {
  width: 50px;
  height: 50px;
  background-color: red;
  /* 수평 중앙 정렬하기 */
  margin: 0 auto;
}

반응형
반응형

 

ValueError: Unable to find resource t64.exe in package pip._vendor.distlib

Python 3.x에서도 pip을 업그레이드할 때 오류가 발생하는 경우가 있다. 이런 경우에는 다음과 같이 upgrade하라는 말만 앵무새처럼 반복하게 된다.

그럴 때에는 get-pip.py 파일을 받아서 실행하면 된다. get-pip.py는 다음 URL에서 받을 수 있는데, 그냥 누르면 파일 내용이 열리므로 마우스 우클릭 후 "다른 이름으로 링크 저장..." 메뉴를 선택하여 get-pip.py란 이름으로 저장한다.


https://bootstrap.pypa.io/get-pip.py

 

get-pip.py를 받은 후에는 저장된 폴더를 열고 그 폴더에서 Shift-우클릭을 통해 명령 프롬프트를 연 다음 일반 Python 프로그램처럼 이를 실행해 준다.


출처: https://woogyun.tistory.com/698 [살아가는 이야기:티스토리]

 

반응형
반응형

프런트엔드 개발자를 위해 꼭 알아야 할 10가지 JavaScript 팁

https://medium.com/@london.lingo.01/10-must-know-javascript-tips-for-front-end-developers-b78b4afe6ad3

 

10 Must-Know JavaScript Tips for Front-End Developers

JavaScript is one of the most popular and powerful programming languages for web development. It allows you to create dynamic and…

medium.com

JavaScript는 웹 개발을 위한 가장 널리 사용되고 강력한 프로그래밍 언어 중 하나입니다. 이를 통해 동적 및 대화형 웹 페이지를 만들고, DOM을 조작하고, 서버와 통신하는 등의 작업을 수행할 수 있습니다. 그러나 JavaScript는 작업하기가 어렵고 좌절스러울 수도 있습니다. 특히 다른 언어에 익숙한 초보자나 개발자에게는 더욱 그렇습니다. 깨끗하고 효율적이며 유지 관리가 가능한 코드를 작성하기 위해 알아야 할 많은 단점, 함정 및 모범 사례가 있습니다.

이번 포스팅에서는 프론트엔드 개발자로서 기술과 생산성을 향상시키는 데 도움이 될 꼭 알아야 할 JavaScript 팁 10가지를 공유하겠습니다. 이 팁에서는 변수, 함수, 문자열, 배열, 개체, 비동기 작업, 모듈, 클래스, 약속 및 콘솔 메서드와 같은 JavaScript의 가장 중요하고 유용한 기능과 개념 중 일부를 다룹니다. 이를 효과적으로 사용하고 일반적인 실수나 오류를 방지하는 방법을 배우게 됩니다. 이 게시물을 마치면 JavaScript에 대해 더 잘 이해하고 더 읽기 쉽고 성능이 뛰어나며 디버그 가능한 코드를 작성하는 방법을 알게 될 것입니다.

그럼 시작해 보겠습니다! 프런트엔드 개발자가 꼭 알아야 할 10가지 JavaScript 팁은 다음과 같습니다.



Tip 1: Use const and let instead of var
One of the most common and confusing issues in JavaScript is the declaration and scope of variables. In the past, JavaScript only had one way to declare variables: using the var keyword. However, var has some drawbacks and limitations that can lead to bugs and errors. For example, var variables are function-scoped, meaning they are accessible within the function where they are declared, but not outside. This can cause problems when you have nested functions or loops that use the same variable name. Also, var variables are hoisted, meaning they are moved to the top of their scope before the code is executed. This can cause problems when you try to access a variable before it is declared or initialized.

To avoid these issues, ES6 introduced two new ways to declare variables: using the const and let keywords. Const and let variables are block-scoped, meaning they are accessible within the block where they are declared, but not outside. This can prevent accidental overwriting or leakage of variables. Also, const and let variables are not hoisted, meaning they are only available after they are declared and initialized. This can prevent accessing undefined or uninitialized variables.

Another difference between const and let is that const variables cannot be reassigned after they are declared. This means that once you assign a value to a const variable, you cannot change it later. This can prevent accidental or intentional modification of variables that should remain constant. Let variables, on the other hand, can be reassigned after they are declared. This means that you can change the value of a let variable as many times as you want.

Here is an example of using const and let to declare variables:

// Using var
var name = "John";
var age = 25;
var hobbies = ["reading", "gaming", "coding"];

function sayHello() {
  var name = "Jane"; // This will overwrite the global name variable
  console.log("Hello, " + name); // Hello, Jane
}

sayHello();
console.log(name); // Jane

// Using const and let
const name = "John"; // This will create a constant name variable
let age = 25; // This will create a let age variable
const hobbies = ["reading", "gaming", "coding"]; // This will create a constant hobbies array

function sayHello() {
  let name = "Jane"; // This will create a local name variable
  console.log("Hello, " + name); // Hello, Jane
}

sayHello();
console.log(name); // John

// You can change the value of a let variable
age = 26;
console.log(age); // 26

// You cannot change the value of a const variable
name = "Jack"; // TypeError: Assignment to constant variable.
hobbies.push("music"); // You can modify the elements of a const array, but not reassign it
console.log(hobbies); // ["reading", "gaming", "coding", "music"]
As you can see, using const and let can make your code more readable, performant and debuggable. It can also help you avoid common errors and bugs that can occur with var variables. Therefore, you should always use const and let instead of var when declaring variables in JavaScript.

Tip 2: Use arrow functions for concise and clean syntax
Another common and important feature of JavaScript is functions. Functions are blocks of code that can be defined and executed to perform a specific task or operation. Functions can also accept parameters and return values. However, functions can also be verbose and complex to write and use, especially when dealing with the this keyword or binding issues.

To simplify and improve the syntax and functionality of functions, ES6 introduced arrow functions. Arrow functions are a shorter and more expressive way to write functions in JavaScript. Arrow functions use the => symbol to separate the parameters and the body of the function. Arrow functions can also omit the parentheses around the parameters if there is only one parameter, and the curly braces and return keyword around the body if there is only one expression.

Here is an example of using arrow functions to write shorter and more expressive code:

// Using regular functions
function add(a, b) {
  return a + b;
}

function greet(name) {
  return "Hello, " + name;
}

function square(x) {
  return x * x;
}

console.log(add(2, 3)); // 5
console.log(greet("John")); // Hello, John
console.log(square(4)); // 16

// Using arrow functions
const add = (a, b) => a + b;
const greet = name => "Hello, " + name;
const square = x => x * x;

console.log(add(2, 3)); // 5
console.log(greet("John")); // Hello, John
console.log(square(4)); // 16
As you can see, using arrow functions can make your code more concise and clean. It can also help you avoid some of the pitfalls and confusion that can occur with regular functions. For example, arrow functions do not have their own this keyword, meaning they inherit the this value from their enclosing scope. This can prevent issues with losing or changing the context of this when using callbacks or methods. Arrow functions also do not have their own arguments object, meaning they rely on the named parameters or the rest operator to access the arguments passed to them. This can prevent issues with accessing or modifying the arguments object in nested or strict mode functions.

Therefore, you should always use arrow functions instead of regular functions when writing concise and clean code in JavaScript.

Tip 3: Use template literals for dynamic and multi-line strings
One of the most common and useful data types in JavaScript is strings. Strings are sequences of characters that can be used to store and manipulate text, such as names, messages, URLs, etc. However, strings can also be tricky and tedious to work with, especially when you need to create dynamic or multi-line strings. For example, you need to use the + operator or the concat method to concatenate strings and variables, and you need to use the \n character or the backslash () to create new lines or escape characters.

To simplify and improve the creation and manipulation of strings, ES6 introduced template literals. Template literals are a new way to write strings in JavaScript that use the backtick (`) character instead of the single (‘) or double (“) quotes. Template literals allow embedding expressions and variables inside strings using the ${} syntax. Template literals also allow creating multi-line strings without using any special characters or escaping.

Here is an example of using template literals to create dynamic and multi-line strings with ease:

// Using regular strings
var name = "John";
var age = 25;
var message = "Hello, " + name + ".\nYou are " + age + " years old.";
console.log(message);
// Hello, John.
// You are 25 years old.

// Using template literals
const name = "John";
const age = 25;
const message = `Hello, ${name}.
You are ${age} years old.`;
console.log(message);
// Hello, John.
// You are 25 years old.
As you can see, using template literals can make your code more readable, interpolation and escaping. It can also help you avoid some of the errors and bugs that can occur with regular strings. For example, template literals do not require any quotation marks around the embedded expressions or variables, meaning they can handle any data type or value without causing syntax errors. Template literals also do not require any special characters or escaping for creating new lines or other characters, meaning they can handle any format or layout without causing display issues.

Therefore, you should always use template literals instead of regular strings when creating dynamic or multi-line strings in JavaScript.

Tip 4: Use destructuring assignment for extracting values from objects and arrays
Another common and useful data type in JavaScript is objects and arrays. Objects and arrays are collections of values that can be used to store and manipulate data, such as properties, methods, elements, etc. However, objects and arrays can also be complex and cumbersome to work with, especially when you need to extract or assign values from them. For example, you need to use the dot (.) or the bracket ([]) notation to access or modify the properties or elements of objects or arrays, and you need to use multiple variables or statements to extract or assign multiple values from them.

To simplify and improve the extraction and assignment of values from objects and arrays, ES6 introduced destructuring assignment. Destructuring assignment is a new way to write assignments in JavaScript that use the {} or [] syntax to unpack values from objects or arrays into variables. Destructuring assignment can also use the = symbol to provide default values or the … symbol to collect the remaining values into a new variable.

Here is an example of using destructuring assignment to simplify code and avoid repetition:

// Using regular assignments
var person = {
  name: "John",
  age: 25,
  hobbies: ["reading", "gaming", "coding"]
};

var name = person.name;
var age = person.age;
var hobbies = person.hobbies;

console.log(name); // John
console.log(age); // 25
console.log(hobbies); // ["reading", "gaming", "coding"]

// Using destructuring assignment
const person = {
  name: "John",
  age: 25,
  hobbies: ["reading", "gaming", "coding"]
};

const { name, age, hobbies } = person;

console.log(name); // John
console.log(age); // 25
console.log(hobbies); // ["reading", "gaming", "coding"]
As you can see, using destructuring assignment can make your code more readable, performant and convenient. It can also help you avoid some of the errors and bugs that can occur with regular assignments. For example, destructuring assignment can handle nested or complex objects or arrays without causing syntax errors. Destructuring assignment can also handle missing or undefined values without causing reference errors.

Therefore, you should always use destructuring assignment instead of regular assignments when extracting or assigning values from objects or arrays in JavaScript.

Tip 5: Use spread and rest operators for manipulating arrays and objects
Another common and important feature of JavaScript is the ability to manipulate arrays and objects. Arrays and objects are collections of values that can be used to store and manipulate data, such as properties, methods, elements, etc. However, arrays and objects can also be difficult and tedious to manipulate, especially when you need to copy, merge or split them. For example, you need to use the slice, concat or splice methods to copy, merge or split arrays, and you need to use the Object.assign or Object.keys methods to copy or merge objects.

To simplify and improve the manipulation of arrays and objects, ES6 introduced the spread and rest operators. The spread operator (…) allows expanding or spreading the values of an array or an object into individual values. The rest operator (…) allows collecting or gathering the remaining values of an array or an object into a new variable.

Here is an example of using the spread and rest operators to manipulate arrays and objects with ease:

// Using regular methods
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

// Copying an array
var arr3 = arr1.slice();
console.log(arr3); // [1, 2, 3]

// Merging two arrays
var arr4 = arr1.concat(arr2);
console.log(arr4); // [1, 2, 3, 4, 5, 6]

// Splitting an array
var arr5 = arr4.splice(0, 3);
console.log(arr5); // [1, 2, 3]
console.log(arr4); // [4, 5, 6]

var obj1 = { name: "John", age: 25 };
var obj2 = { hobbies: ["reading", "gaming", "coding"] };

// Copying an object
var obj3 = Object.assign({}, obj1);
console.log(obj3); // { name: "John", age: 25 }

// Merging two objects
var obj4 = Object.assign({}, obj1, obj2);
console.log(obj4); // { name: "John", age: 25, hobbies: ["reading", "gaming", "coding"] }

// Using spread and rest operators
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// Copying an array
const arr3 = [...arr1];
console.log(arr3); // [1, 2, 3]

// Merging two arrays
const arr4 = [...arr1, ...arr2];
console.log(arr4); // [1, 2, 3, 4, 5, 6]

// Splitting an array
const [first, second, third] = arr1;
console.log(first); // 1
console.log(second); // 2
console.log(third); // 3

const [head,...tail] = arr4;
console.log(head); // 1
console.log(tail); // [2 ,3 ,4 ,5 ,6]

const obj1 = { name: "John", age: 25 };
const obj2 = { hobbies: ["reading", "gaming", "coding"] };

// Copying an object
const obj3 = {...obj1};
console.log(obj3); // { name: "John", age: 25 }

// Merging two objects
const obj4 = {...obj1,...obj2};
console.log(obj4); // { name: "John", age: 25,hobbies: ["reading", "gaming", "coding"] }
As you can see, using the spread and rest operators can make your code more readable flexibility and immutability. It can also help you avoid some of the errors and bugs that can occur with regular methods. For example, the spread operator can handle nested or complex arrays or objects without causing syntax errors. The rest operator can handle missing or undefined values without causing reference errors.

Therefore, you should always use the spread and rest operators instead of regular methods when manipulating arrays or objects in JavaScript.

Tip 6: Use async/await for handling asynchronous operations
Another common and important feature of JavaScript is the ability to handle asynchronous operations. Asynchronous operations are tasks or functions that can run in the background without blocking the main thread of execution. Asynchronous operations can be used to perform tasks such as fetching data from a server, reading or writing files, setting timers, etc. However, asynchronous operations can also be challenging and complex to handle, especially when dealing with callbacks, promises or errors.

To simplify and improve the handling of asynchronous operations, ES8 introduced async/await. Async/await is a new way to write asynchronous code in JavaScript that uses the async and await keywords. The async keyword allows defining an asynchronous function that returns a promise. The await keyword allows pausing the execution of an asynchronous function until a promise is resolved or rejected.

Here is an example of using async/await to handle asynchronous operations with ease:

// Using callbacks
function fetchData(url, callback) {
  // Simulate fetching data from a server
  setTimeout(() => {
    const data = "Some data from " + url;
    callback(null, data);
  }, 1000);
}

function processData(data, callback) {
  // Simulate processing data
  setTimeout(() => {
    const result = "Processed " + data;
    callback(null, result);
  }, 1000);
}

function displayData(data, callback) {
  // Simulate displaying data
  setTimeout(() => {
    console.log(data);
    callback(null, "Done");
  }, 1000);
}

// Using nested callbacks to handle asynchronous operations
fetchData("https://example.com", (err1, data1) => {
  if (err1) {
    console.error(err1);
  } else {
    processData(data1, (err2, data2) => {
      if (err2) {
        console.error(err2);
      } else {
        displayData(data2, (err3, data3) => {
          if (err3) {
            console.error(err3);
          } else {
            console.log(data3); // Done
          }
        });
      }
    });
  }
});

// Using async/await
async function fetchData(url) {
  // Simulate fetching data from a server
  return new Promise(resolve => {
    setTimeout(() => {
      const data = "Some data from " + url;
      resolve(data);
    }, 1000);
  });
}

async function processData(data) {
  // Simulate processing data
  return new Promise(resolve => {
    setTimeout(() => {
      const result = "Processed " + data;
      resolve(result);
    }, 1000);
  });
}

async function displayData(data) {
  // Simulate displaying data
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(data);
      resolve("Done");
    }, 1000);
  });
}

// Using async/await to handle asynchronous operations
async function main() {
  try {
    const data1 = await fetchData("https://example.com");
    const data2 = await processData(data1);
    const data3 = await displayData(data2);
    console.log(data3); // Done
  } catch (error) {
    console.error(error);
  }
}

main();
As you can see, using async/await can make your code more readable error handling and simplicity. It can also help you avoid some of the pitfalls and confusion that can occur with callbacks or promises. For example, async/await can handle nested or sequential asynchronous operations without causing callback hell or promise chaining. Async/await can also handle errors or rejections using the try/catch blocks or the .catch() method.

Therefore, you should always use async/await instead of callbacks or promises when handling asynchronous operations in JavaScript.

Tip 7: Use modules for organizing and reusing code
Another common and important feature of JavaScript is the ability to organize and reuse code. Code organization and reuse can help you write code that is more readable, maintainable and modular. However, code organization and reuse can also be difficult and tedious to achieve, especially when dealing with multiple files or dependencies.

To simplify and improve the organization and reuse of code, ES6 introduced modules. Modules are a new way to write code in JavaScript that use the import and export keywords. Modules allow dividing code into separate files that can be imported and exported as needed. Modules can also use the default or named syntax to specify what values or features are exported or imported.

Here is an example of using modules to organize and reuse code with ease:

// math.js file
// Exporting a default value
export default function add(a, b) {
  return a + b;
}

// Exporting named values
export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  return a / b;
}

// app.js file
// Importing a default value
import add from "./math.js";

console.log(add(2, 3)); // 5

// Importing named values
import { subtract, multiply, divide } from "./math.js";

console.log(subtract(5, 2)); // 3
console.log(multiply(2, 3)); // 6
console.log(divide(6, 2)); // 3

// Importing all values as an object
import * as math from "./math.js";

console.log(math.add(2, 3)); // 5
console.log(math.subtract(5, 2)); // 3
console.log(math.multiply(2, 3)); // 6
console.log(math.divide(6, 2)); // 3
As you can see, using modules can make your code more readable maintainability and modularity. It can also help you avoid some of the errors and bugs that can occur with regular scripts or dependencies. For example, modules can handle scope or naming conflicts without causing syntax errors. Modules can also handle loading or caching issues without causing performance or memory issues.

Therefore, you should always use modules instead of regular scripts or dependencies when organizing and reusing code in JavaScript.

Tip 8: Use classes for creating objects with shared properties and methods
Another common and useful data type in JavaScript is objects. Objects are collections of values that can be used to store and manipulate data, such as properties, methods, etc. However, objects can also be complex and cumbersome to create and use, especially when you need to create multiple objects with a common structure and behavior.

To simplify and improve the creation and use of objects, ES6 introduced classes. Classes are a new way to write objects in JavaScript that use the class keyword. Classes allow defining a constructor, properties and methods for an object. Classes can also use the extends or super keywords to implement inheritance or polymorphism.

Here is an example of using classes to create objects with shared properties and methods with ease:

// Using regular objects
function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function () {
  console.log("Hello, I am " + this.name + " and I am " + this.age + " years old.");
};

function Student(name, age, course) {
  Person.call(this, name, age);
  this.course = course;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

Student.prototype.study = function () {
  console.log("I am studying " + this.course + ".");
};

var john = new Person("John", 25);
var jane = new Student("Jane", 22, "Computer Science");

john.greet(); // Hello, I am John and I am 25 years old.
jane.greet(); // Hello, I am Jane and I am 22 years old.
jane.study(); // I am studying Computer Science.

// Using classes
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, I am ${this.name} and I am ${this.age} years old.`);
  }
}

class Student extends Person {
  constructor(name, age, course) {
    super(name, age);
    this.course = course;
  }

  study() {
    console.log(`I am studying ${this.course}.`);
  }
}

const john = new Person("John", 25);
const jane = new Student("Jane", 22, "Computer Science");

john.greet(); // Hello, I am John and I am 25 years old.
jane.greet(); // Hello, I am Jane and I am 22 years old.
jane.study(); // I am studying Computer Science.
As you can see, using classes can make your code more readable encapsulation and inheritance. It can also help you avoid some of the errors and bugs that can occur with regular objects. For example, classes can handle constructor or prototype issues without causing syntax errors. Classes can also handle inheritance or polymorphism issues without causing reference errors.

Therefore, you should always use classes instead of regular objects when creating objects with shared properties and methods in JavaScript.

Tip 9: Use promises for handling asynchronous operations
Another common and important feature of JavaScript is the ability to handle asynchronous operations. Asynchronous operations are tasks or functions that can run in the background without blocking the main thread of execution. Asynchronous operations can be used to perform tasks such as fetching data from a server, reading or writing files, setting timers, etc. However, asynchronous operations can also be challenging and complex to handle, especially when dealing with callbacks or errors.

To simplify and improve the handling of asynchronous operations, ES6 introduced promises. Promises are a new way to write asynchronous code in JavaScript that use the Promise object. Promises represent the eventual completion or failure of an asynchronous operation. Promises can also use the then or catch methods to handle the resolution or rejection of an asynchronous operation.

Here is an example of using promises to handle asynchronous operations with ease:

// Using callbacks
function fetchData(url, callback) {
  // Simulate fetching data from a server
  setTimeout(() => {
    const data = "Some data from " + url;
    callback(null, data);
  }, 1000);
}

function processData(data, callback) {
  // Simulate processing data
  setTimeout(() => {
    const result = "Processed " + data;
    callback(null, result);
  }, 1000);
}

function displayData(data, callback) {
  // Simulate displaying data
  setTimeout(() => {
    console.log(data);
    callback(null, "Done");
  }, 1000);
}

// Using nested callbacks to handle asynchronous operations
fetchData("https://example.com", (err1, data1) => {
  if (err1) {
    console.error(err1);
  } else {
    processData(data1, (err2, data2) => {
      if (err2) {
        console.error(err2);
      } else {
        displayData(data2, (err3, data3) => {
          if (err3) {
            console.error(err3);
          } else {
            console.log(data3); // Done
          }
        });
      }
    });
  }
});

// Using promises
function fetchData(url) {
  // Simulate fetching data from a server
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "Some data from " + url;
      resolve(data);
    }, 1000);
  });
}

function processData(data) {
  // Simulate processing data
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const result = "Processed " + data;
      resolve(result);
    }, 1000);
  });
}

function displayData(data) {
  // Simulate displaying data
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(data);
      resolve("Done");
    }, 1000);
  });
}

// Using promises to handle asynchronous operations
fetchData("https://example.com")
  .then(data1 => processData(data1))
  .then(data2 => displayData(data2))
  .then(data3 => console.log(data3)) // Done
  .catch(error => console.error(error));
As you can see, using promises can make your code more readable error handling and simplicity. It can also help you avoid some of the pitfalls and confusion that can occur with callbacks or errors. For example, promises can handle nested or sequential asynchronous operations without causing callback hell or pyramid of doom. Promises can also handle errors or rejections using the catch method or the reject function.

Therefore, you should always use promises instead of callbacks or errors when handling asynchronous operations in JavaScript.

Tip 10: Use console methods for debugging and testing code
Another common and important feature of JavaScript is the ability to debug and test code. Debugging and testing code can help you find and fix errors or bugs in your code, as well as improve its performance or functionality. However, debugging and testing code can also be difficult and tedious to do, especially when dealing with complex or large code.

To simplify and improve the debugging and testing of code, JavaScript provides various console methods. Console methods are built-in functions that can be used to log, inspect or test values in the browser console. Console methods can also use various parameters or options to customize the output or behavior of the console.

Here is an example of using console methods to debug and test code with ease:

// Using console.log
console.log("Hello, world!"); // Hello, world!
console.log(2 + 3); // 5
console.log({ name: "John", age: 25 }); // { name: "John", age: 25 }

// Using console.table
console.table(["apple", "banana", "orange"]); // Displays a table with index and value columns
console.table({ name: "John", age: 25 }); // Displays a table with key and value columns

// Using console.assert
console.assert(2 > 3, "2 is not greater than 3"); // Assertion failed: 2 is not greater than 3
console.assert(3 > 2, "3 is greater than 2"); // No output

// Using console.time and console.timeEnd
console.time("Loop"); // Starts a timer with the label Loop
for (let i = 0; i < 1000000; i++) {
  // Do something
}
console.timeEnd("Loop"); // Ends the timer and logs the elapsed time
// Loop: 3.456 ms

// Using console.group and console.groupEnd
console.group("Animals"); // Starts a group with the label Animals
console.log("Cat");
console.log("Dog");
console.log("Bird");
console.groupEnd(); // Ends the group
// Animals:
//   Cat
//   Dog
//   Bird
As you can see, using console methods can make your code more readable performance and troubleshooting. It can also help you avoid some of the errors and bugs that can occur with regular logging or testing. For example, console methods can handle different data types or values without causing syntax errors. Console methods can also handle formatting or grouping issues without causing display issues.

Therefore, you should always use console methods instead of regular logging or testing when debugging and testing code in JavaScript.

반응형
반응형

Polacode

 

https://marketplace.visualstudio.com/items?itemName=pnp.polacode

 

Polacode - Visual Studio Marketplace

Extension for Visual Studio Code - 📸 Polaroid for your code

marketplace.visualstudio.com

 

Why?

You have spent countless hours finding the perfect JavaScript grammar, matching it with a sleek-looking VS Code theme, trying out all the best programming fonts.

You take three days porting over your theme before starting to use VS Code.
You shell out $200 for italic cursive html attributes.

The code has to look right.

Tips

  • Resize the snippet / container by dragging the lowerright corner
  • Use polacode.target, polacode.shadow, polacode.transparentBackground and polacode.backgroundColor to control image appearance
반응형
반응형

※ CHARINDEX() 함수와 SUBSTRING함수를 이용한 분리

DECLARE @DATA VARCHAR(MAX), @separator CHAR, @substring varchar(max), @dividepos INT, @tot_cnt int

set @data = 'a,bb,ccc,ddd,eeeee,ffffff,gggggggg,hhhhhh,iiiiiiiii' 
set @separator = ','
set @dividepos = CHARINDEX(@separator, @data)
set @tot_cnt = 0

while @dividepos <> 0 or len(@data) > 0
begin
set @dividepos = CHARINDEX(@separator,@data)
if( @dividepos = 0 )
begin
set @substring = @data
set @data = ''
end
else
begin
select @substring = SUBSTRING(@data,1,@dividepos - 1)
set @data = SUBSTRING(@data, @dividepos +1, len(@data))
end 
set @tot_cnt = @tot_cnt + 1

-- select @substring, @tot_cnt

end

 

---※ CHARINDEX() 함수와 SUBSTRING함수를 이용한 분리

DECLARE @DATA VARCHAR(MAX), @separator CHAR, @substring varchar(max), @dividepos INT, @tot_cnt int

set @data = 'a,bb,ccc,ddd,eeeee,ffffff,gggggggg,hhhhhh,iiiiiiiii' 
set @separator = ','
set @dividepos = CHARINDEX(@separator, @data)
set @tot_cnt = 0

while @dividepos <> 0 or len(@data) > 0
begin
	set @dividepos = CHARINDEX(@separator,@data)
	if( @dividepos = 0 )
	begin
		set @substring = @data
		set @data = ''
	end
	else
	begin
		select @substring = SUBSTRING(@data,1,@dividepos - 1)
		set @data = SUBSTRING(@data, @dividepos +1, len(@data))
	end 
	set @tot_cnt = @tot_cnt + 1

	-- select @substring, @tot_cnt

end
반응형
반응형

https://stfalconcom.medium.com/flutter-vs-react-native-ae79df948a16

 

Flutter vs. React Native

Let's start the analysis of the topic, which is better to select Flutter or React Native for work, it’s necessary to recognize where it all…

stfalconcom.medium.com

작업을 위해 Flutter 또는 React Native를 선택하는 것이 더 나은 주제 분석을 시작하겠습니다. 모든 것이 어디서 시작되었는지 인식해야 합니다. DataReportal의 Digital 2022 Global Statshot 통계 및 보고서에 따르면 지구상의 거의 70%의 사람들이 매일 휴대전화를 사용합니다.

즉, 현대인의 라이프스타일이 모바일 애플리케이션 산업에 엄청난 수혜를 안겨준 셈이다. 그러므로 따라서 후자를 개발하는 경우는 여전히 매우 적절하다. 결국 오늘날의 기술 리더인 Google과 Facebook이 만든 Flutter & React Native가 등장합니다.

우리는 다음 질문을 고려하여 본 연구에서 어떤 것을 선택하는 것이 더 나은지 논의할 것입니다.

본 연구에서는 다음 질문을 고려하여 완벽한 선택에 대해 논의할 것입니다.

  • 반응이란 무엇입니까?
  • 플러터란 무엇인가요?
  • 2023년에 무엇을 선택할 것인가: Flutter 또는 React Native?
  • 마지막 생각들.

Flutter 및 React 앱 개발에 대한 풍부한 정보가 매일 인터넷에 넘쳐나는 시대에 우리는 더 깊이 탐구한다는 점을 강조하는 것이 중요합니다. 이 글에서는 Flutter와 React Native의 중요한 차이점을 살펴보고 차이점을 살펴보겠습니다.

그럼, 조사를 시작하겠습니다!

리액트 네이티브와 Flutter

Flutter와 React Native의 비교는 새로운 것이 아니며 광범위하게 논의된 주제입니다. 그러나 어떤 도구가 더 우수한지에 대한 질문에 대한 명확한 답은 아직 파악하기 어렵습니다. 두 프레임워크 모두 열광적인 헌신적인 커뮤니티와 함께 ​​각각의 장점과 단점을 가지고 있습니다. 이 기사의 목표는 Flutter와 React Native에 대한 포괄적인 이해를 제공하여 이러한 하이브리드 기술의 복잡성을 보다 효과적으로 탐색할 수 있도록 하는 것입니다. 이러한 지식을 바탕으로 정보에 입각한 선택을 하고 선호도에 맞는 도구를 선택하는 데 더 많은 준비를 갖추게 될 수 있습니다.

Flutter와 React Native의 비교는 그렇지 않으며 이미 충분히 논의된 주제입니다. 더욱이 어떤 도구가 최고의 도구인지에 대한 결정적인 답변은 여전히 ​​어렵습니다. 두 프레임워크 모두 고유한 강점과 약점을 갖고 있으며, 각 프레임워크에는 열렬한 지지자 커뮤니티가 수반됩니다. 이 기사의 목표는 Flutter 및 React Native에 대한 포괄적인 이해를 제공하여 이러한 하이브리드 기술의 복잡성을 더욱 능숙하게 탐색할 수 있도록 지원하는 것입니다. 이러한 지식을 통해 귀하는 현명한 결정을 내리고 귀하의 선호도에 가장 적합한 도구를 선택할 수 있는 준비를 갖추게 될 것입니다.

플러터는 무슨 뜻인가요?

Flutter에 대해 이야기하기 시작할 때 이것이 모바일 앱이나 휴대용 소비자 인터페이스 도구 키트를 만들기 위한 크로스 플랫폼 플랫폼이라는 점을 정확히 말할 필요가 있습니다. 개발자에게 도구 및 위젯으로 구성된 완전한 소프트웨어 개발 키트(SDK)를 제공합니다.

Flutter로 데스크톱 앱을 만들 때 Flutter 소스 코드를 기본 Windows, Linux 또는 macOS 데스크톱 앱으로 수집할 수 있습니다. 예를 들어 Flutter의 웹 지원은 인터넷 및 모바일 장치에서 동일한 프로세스를 제공합니다. 이는 이제 동일한 코드베이스에서 iOS, Android 및 웹 브라우저용 애플리케이션을 만들 수 있음을 의미합니다.

Google 팀에서 개발하고 Dart를 기반으로 구축된 Flutter는 무료이면서도 비교적 새로운 기능으로, 접근성이 뛰어나고 이해하기 쉽습니다. 고성능 렌더링 엔진으로 구동되는 사용자 정의 위젯 컬렉션을 제공합니다. 특히 Google과 Flutter 커뮤니티는 지속적인 개발에 적극적으로 기여하고 있습니다. 결과적으로 Flutter는 자신있게 신흥 기술로 분류될 수 있습니다.

초기 반복에서 Flutter는 Android 및 iOS와 호환되는 모바일 애플리케이션을 만들기 위한 툴킷을 제공했습니다. 후속 버전을 통해 발전하면서 Flutter는 다양한 플랫폼에 대한 지원을 포괄하도록 범위를 확장했습니다. 이 확장에는 Windows, macOS, Linux, 웹 애플리케이션 및 Flutter 사용을 위해 맞춤 제작된 특수 플랫폼이 포함되었습니다. 특히 2023년 1월 Flutter 3.7의 출시는 중요한 이정표였습니다. 이 업데이트에는 iOS에 최적화된 렌더링 엔진, Material 3 및 iOS 스타일 위젯에 대한 향상된 지원, 향상된 현지화 솔루션, 더욱 효율적인 배경 데이터 처리, 개발 도구 개선 등 다양한 새로운 기능이 도입되었습니다.

반응은 무엇을 의미합니까?

반면 React Native는 JavaScript를 활용하고 Facebook에서 제작한 모바일 앱용 오픈 소스 프레임워크입니다.

2023년에 React Native를 배워야 하는 가장 강력한 이유 중 하나는 플랫폼 독립성입니다. 과거에는 개발자들이 Android 애플리케이션 개발에는 Java를, iOS 애플리케이션 개발에는 Swift를 주로 활용해야 했습니다. 게다가 Windows와 같은 다른 플랫폼도 있어서 프로세스가 더 복잡해졌습니다. React Native는 여러 플랫폼에서 원활하게 실행되는 앱을 만들기 위한 완벽한 옵션으로 등장합니다. React Native를 사용하면 앱을 한 번만 빌드하면 모든 주요 플랫폼에서 쉽게 실행됩니다. 또한 React Native는 React에 익숙한 사람들에게 친숙한 JSX를 활용하며 종종 HTML과 JavaScript의 혼합으로 정의됩니다. 이러한 친숙함 덕분에 일부 어려운 개념에도 불구하고 React Native를 비교적 쉽게 배울 수 있습니다. 유사한 목표를 위해 Java를 활용하는 것과 비교할 때 React Native를 사용한 구성 앱은 훨씬 더 쉽고 효율적입니다.

React Native는 Flutter보다 오래되었으며 더 큰 커뮤니티를 자랑한다는 점을 강조해야 합니다. 계속 읽어보자!

React와 Native Flutter의 차이점

아래에서는 두 프레임워크의 장점과 단점에 대해 설명하겠습니다.

기본 성능 비교

Flutter는 AOT(Ahead-of-Time) 컴파일러를 활용하여 프로젝트가 빌드된 후 iOS 및 Android에 최적화된 코드를 생성하여 애플리케이션 바이너리에 전체 코드베이스를 포함할 필요 없이 네이티브 수준의 성능을 보장합니다. 이는 React Native와 공통된 기능입니다. . 특히, 네이티브 모듈과 상호작용하기 위해 브리지를 요구하는 React Native와 달리 Flutter는 네이티브 모듈과 직접 통신합니다.

React Native는 JIT 컴파일러 덕분에 V8보다 뛰어난 향상된 JavaScript 가상 머신을 자랑합니다. 사전 컴파일된 프레임워크로서 모든 코드베이스를 배포하고 기본 실행 파일로 컴파일할 수 있습니다. 일반적으로 React Native는 iOS 빌드 설정을 조정할 필요 없이 iOS 애플리케이션 수준에서 수행하여 기본 앱과 동일한 속도를 달성합니다.

React Native는 JIT 컴파일러 덕분에 성능 면에서 V8을 능가하는 뛰어난 JavaScript 가상 머신을 갖추고 있습니다. 사전 컴파일된 프레임워크로서 모든 코드베이스를 기본 실행 파일로 배포하고 컴파일하는 것을 용이하게 합니다. 일반적으로 React Native는 iOS 빌드 설정을 수정할 필요 없이 iOS 애플리케이션 수준에서 수행하여 기본 앱과 동일한 속도를 달성합니다.

결론 : Flutter와 React Native 모두 네이티브 수준의 높은 성능을 자랑하지만 Flutter는 네이티브 모듈과 직접 통신합니다.

프로그래밍 언어

React Native는 동적 웹 개발을 가능하게 하는 최초의 언어인 고전적인 JavaScript 프로그래밍 언어를 활용합니다.

Flutter는 2011년에 발표된 이후 훨씬 새로운 언어인 Dart를 활용합니다.

JavaScript는 Dart에 비해 더 광범위하고 광범위하게 사용됩니다. 결과적으로 개발자는 React Native 애플리케이션 개발에 뛰어드는 것이 더 익숙하고 편안하다고 생각하는 경우가 많습니다.

결론: Flutter와 React Native 프로그래밍 언어 모두 무결성이 있지만 React Native가 승리합니다.

신뢰할 수 있음

안정적인 플랫폼을 사용하여 모바일 애플리케이션을 신속하게 개발하는 것이 우선이라면 Flutter가 더 나은 옵션이 될 수 있습니다. 반대로, 강력한 지원 생태계와 강력한 UI 기능을 자랑하는 잘 확립된 플랫폼을 찾고 있다면 React Native가 더 적절한 선택일 수 있습니다.

결론 : React Native와 Flutter는 모두 안정적이지만 React Native는 강력한 지원 생태계를 갖추고 있습니다.

소비자 인터페이스 구축

React Native 프레임워크는 Flutter의 규모를 능가하는 광범위하고 활발한 커뮤니티로 돋보입니다. 풍부한 UI 디자인, 라이브러리, 철저한 문서 및 수많은 보충 리소스를 제공합니다. 또한 React Native는 Flutter와 비교할 때 훨씬 더 풍부한 타사 라이브러리를 자랑합니다.

결론: React Native는 소비자 인터페이스를 구축하는 데 가장 적합한 옵션입니다.

선적 서류 비치

Flutter에는 Android와 iOS 모두에 대한 명확한 플랫폼 설정 및 IDE 정보가 있습니다. 명령줄 인터페이스(CLI)도 개발자의 설정을 지원하는 도구인 Flutter Doctor와 함께 제공됩니다.

오픈 소스 특성 덕분에 Flutter는 뛰어난 사용자 정의 및 유연성을 제공하므로 개발자는 독특한 소비자 경험을 쉽게 준비할 수 있습니다.

React Native는 새로운 업데이트가 나올 때마다 계속해서 발전하고 있습니다. 계속해서 교육을 받으려면 React Native의 공식 문서 와 웹 리소스를 주의 깊게 살펴보세요 .

결론: Flutter는 포괄적인 문서를 자랑하지만 React Native는 끊임없이 진화하고 있습니다.

설치 용이성

React Native 설치는 간단하지만 패키지를 생성하므로 일부 개발자에게는 사소한 불편함으로 보일 수 있습니다. 그러나 이 요소는 사용자마다 중요도가 다릅니다. React Native는 주로 UI 렌더링 및 장치 액세스 API를 제공하며 해당 기능을 보완하기 위해 타사 라이브러리에 의존한다는 점은 주목할 가치가 있습니다.

React Native 설치는 간단한 프로세스이지만 패키지 생성이 포함되어 있어 특정 개발자에게는 사소한 불편으로 간주될 수 있습니다. 이 요소의 중요성은 사용자마다 다르다는 점을 강조하는 것이 중요합니다. 또한 React Native는 기능 향상을 위해 타사 라이브러리에 따라 주로 UI 렌더링 및 장치 액세스 API를 제안한다는 점에 주목할 가치가 있습니다.

Flutter는 작은 ZIP 파일에서 얻을 수 있지만 명령줄에서 PATH 변수로 추가해야 합니다. 이것은 일을 불필요하게 어렵게 만듭니다.

결론: React Native는 Flutter보다 설정하기가 훨씬 쉽습니다.

지역 사회

React Native는 Flutter보다 앞서며 더 큰 커뮤니티를 자랑합니다. 또한 Meta 팀은 API를 개선하고 근본적인 문제를 해결하는 데 많은 시간을 보냈습니다.

React Native는 버전 0.70부터 기본 엔진이었던 새로운 JavaScript 엔진 Hermes를 채택하여 성능 최적화 및 메모리 사용량 감소 측면에서 상당한 진전을 이루었습니다. 이에 대한 더 자세한 내용은 React Native 블로그 게시물을 참조하세요.

또한 Meta는 다음과 같은 몇 가지 중요한 개선 작업을 적극적으로 진행하고 있습니다.

  • 린 코어(Lean Core): 여기에는 선택적 구성 요소나 기능을 별도의 저장소에 재배치하여 개발자가 필요에 따라 이를 애플리케이션에 추가할 수 있도록 하여 애플리케이션의 크기를 줄이는 것이 포함됩니다.
  • React Native Fabric: 성능 향상을 위해 재구성된 UI 레이어입니다.
  • TurboModules: 이는 기본 모듈 처리를 개선하는 것을 목표로 합니다.

결론: React Native는 이제 Flutter에 비해 더 크고 강력한 커뮤니티 지원을 자랑합니다.

디버깅

React Native에서는 디버깅이 어려울 수 있습니다. 특히 앱의 기본 부분 어딘가에 특정 예외나 실수가 나타날 경우 더욱 그렇습니다.

반면 Flutter는 Android Studio 및 Visual Studio와 원활하게 통합되는 도구를 제공하여 디버깅 프로세스를 단순화하고 개발 워크플로를 간소화합니다.

결론: Flutter가 이 비교에서 승리했습니다.

인기

2023년 현재 Flutter와 React Native라는 두 가지 주요 하이브리드 앱 개발 프레임워크가 계속해서 업계를 지배하고 있습니다. 놀랍게도 두 프레임워크의 인기는 계속 높아지고 있습니다. 2023년에는 42%의 개발자가 앱 개발을 위해 React Native를 선호했으며, Flutter가 39%로 그 뒤를 바짝 쫓고 있습니다.

올해인 2023년에도 Flutter와 React Native라는 두 가지 주요 하이브리드 앱 개발 프레임워크가 여전히 영향력을 행사하고 있습니다. 흥미롭게도 두 프레임워크의 매력이 계속 높아지고 있습니다. 올해 React Native는 개발자 중 42%가 애플리케이션 개발을 선호했으며, Flutter가 39%로 그 뒤를 바짝 쫓고 있습니다.

결론: React Native는 인기로 승리합니다.

위의 내용을 표로 요약해 보겠습니다.

계속하자!

2023년에 무엇을 선택할 것인가: React Native 또는 Flutter

Flutter를 선택할지, React Native를 선택할지 고민할 때 명확하거나 간단한 대답이 없다는 점에 유의하는 것이 중요합니다. 두 옵션 모두 실행 가능한 선택입니다.

우리가 알 수 있는 한, React Native와 Flutter는 공통점이 많지만 많지는 않습니다. 첫 번째이자 가장 중요한 사실은 둘 다 누구나 활용할 수 있는 오픈 소스 프레임워크라는 것입니다.

Flutter 프레임워크와 그것이 2023년 프로젝트에 적합한 선택인지에 대해 여전히 질문이 있는 경우 이 주제에 대한 연구 중 하나를 읽어 보시기 바랍니다 .

2023년에 어떤 기술이 승자가 될지 정의하는 것은 간단한 과제가 아닙니다. React Native와 Flutter는 모두 다양한 장단점을 보여줍니다. Flutter는 크로스 플랫폼 모바일 앱을 만들기 위한 신속하고 신뢰할 수 있는 프레임워크로 두각을 나타내며, 다양한 오픈 소스 라이브러리 및 강력한 플러그인 생태계에 대한 액세스를 제안합니다. 반면에 React Native는 개발자가 JavaScript를 활용하여 복잡한 소비자 인터페이스를 만들 수 있도록 지원하고 광범위하고 헌신적인 개발 커뮤니티의 이점을 누릴 수 있습니다.

궁극적으로 이 두 프레임워크 사이의 선택은 아마도 개인의 필요와 선호도에 달려 있을 것입니다. 신속한 모바일 애플리케이션 개발을 촉진하는 빠르고 안정적인 플랫폼을 우선시한다면 Flutter가 더 나은 선택일 수 있습니다. 게다가, 포괄적인 지원과 강력한 UI 기능을 갖춘 잘 확립된 플랫폼을 찾고 있다면 React Native가 귀하의 요구에 더 나은 옵션이 될 수 있습니다.

반응형

+ Recent posts