web developer

[javaScript] When to Use Arrays. When to use Objects. 본문

JavaScript

[javaScript] When to Use Arrays. When to use Objects.

trueman 2022. 1. 6. 14:47
728x90
728x90

When to Use Arrays. When to use Objects.

  • JavaScript does not support associative arrays.
  • You should use objects when you want the element names to be strings (text)
  • You should use arrays when you want the element names to be numbers.

개체 속성에 접근할 수 있는 방법 2가지

1) objectName.propertyName

2) objectName["propertyName"]

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>If you use a named index when accessing an array, JavaScript will redefine the array to a standard object, and some array methods and properties will produce undefined or incorrect results.</p>

<p id="demo"></p>

<script>

// 1번 (정상) - array
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46; 
document.getElementById("demo").innerHTML =
person[0] + " " + person.length;

// 2번 (오류) - err
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46; 

document.getElementById("demo").innerHTML =
person[0] + " " + person.length;

// 3번 (정상) - let
let firstName = 0;
let lastName = 1;
let age = 2;

const person = [];
person[firstName] = "John";
person[lastName] = "Doe";
person[age] = 46; 

// 4번 (정상) - object
let df = {
firstName : 0
,lastName : 1
,age : 2
}

const person = [];
person[df.firstName] = "John";
person[df.lastName] = "Doe";
person[df.age] = 46;

document.getElementById("demo").innerHTML =
person[0] + " " + person.length;
</script>

</body>
</html>

출처 : https://www.w3schools.com/js/js_arrays.asp

 

JavaScript Arrays

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

728x90
728x90
Comments